package com.elinkway.infinitemovies.ui.activity.play;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.bestv.app.view.InitShellApplicationContextListener;
import com.bestv.app.view.VideoViewShell;
import com.elinkway.infinitemovies.adaction.CommonAdActionHandle;
import com.elinkway.infinitemovies.adapter.EpisodeLocalPlayAdapter;
import com.elinkway.infinitemovies.adapter.EpisodePagerAdapter;
import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.async.MoviesHttpAsyncTask;
import com.elinkway.infinitemovies.async.NewRequestResultListener;
import com.elinkway.infinitemovies.async.RequestCloudDiskTask;
import com.elinkway.infinitemovies.async.RequestCloudErrorTask;
import com.elinkway.infinitemovies.async.RequestOutSiteStreamInfoTask;
import com.elinkway.infinitemovies.async.RequestResultListener;
import com.elinkway.infinitemovies.async.RequestStreamResultListener;
import com.elinkway.infinitemovies.async.RequestVStreamListTask;
import com.elinkway.infinitemovies.async.RequestVideoPageInfoTask;
import com.elinkway.infinitemovies.async.ThirdAdReportTask;
import com.elinkway.infinitemovies.async.UpLoadLocalStreamTask;
import com.elinkway.infinitemovies.async.UpdatestreamTask;
import com.elinkway.infinitemovies.bean.CloudDiskBean;
import com.elinkway.infinitemovies.bean.CloudErrorBean;
import com.elinkway.infinitemovies.bean.Episode;
import com.elinkway.infinitemovies.bean.FsTokenBean;
import com.elinkway.infinitemovies.bean.HzAdBean;
import com.elinkway.infinitemovies.bean.HzPayload;
import com.elinkway.infinitemovies.bean.LocalVideoEpisode;
import com.elinkway.infinitemovies.bean.MsgBean;
import com.elinkway.infinitemovies.bean.NewAdDataBean;
import com.elinkway.infinitemovies.bean.OutSiteStreamEntity;
import com.elinkway.infinitemovies.bean.OutSiteStreamInfo;
import com.elinkway.infinitemovies.bean.PageInfoData;
import com.elinkway.infinitemovies.bean.Payload;
import com.elinkway.infinitemovies.bean.PlayData;
import com.elinkway.infinitemovies.bean.PlayRecord;
import com.elinkway.infinitemovies.bean.PlayStatusReporter;
import com.elinkway.infinitemovies.bean.PostCloudErrorBean;
import com.elinkway.infinitemovies.bean.SDKPayload;
import com.elinkway.infinitemovies.bean.ServerPayload;
import com.elinkway.infinitemovies.bean.SingleInfo;
import com.elinkway.infinitemovies.bean.TtPayload;
import com.elinkway.infinitemovies.bean.UMengReport;
import com.elinkway.infinitemovies.bean.UpLoadLocalStreamBean;
import com.elinkway.infinitemovies.bean.UpdatestreamBean;
import com.elinkway.infinitemovies.bean.VStreamInfoList;
import com.elinkway.infinitemovies.bean.XfPayload;
import com.elinkway.infinitemovies.bean.YzPayload;
import com.elinkway.infinitemovies.bigdata.BigDataApi;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.bigdata.BigDataPlayReporter;
import com.elinkway.infinitemovies.bigdata.BigDataUtils;
import com.elinkway.infinitemovies.config.SettingManage;
import com.elinkway.infinitemovies.dao.DownLoadPlayRecordDao;
import com.elinkway.infinitemovies.dao.PlayRecordDao;
import com.elinkway.infinitemovies.dao.PreferencesManager;
import com.elinkway.infinitemovies.download.Constants;
import com.elinkway.infinitemovies.download.DownloadEntity;
import com.elinkway.infinitemovies.download.DownloadManager;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi.LeTvBitStreamParam;
import com.elinkway.infinitemovies.http.parser.FsTokenParser;
import com.elinkway.infinitemovies.http.posttask.PostCloudErrorDataTask;
import com.elinkway.infinitemovies.http.requesttask.ReportPlaySessionTask;
import com.elinkway.infinitemovies.http.requesttask.ReportPlayStatusTask;
import com.elinkway.infinitemovies.http.requesttask.RequestAdTask;
import com.elinkway.infinitemovies.http.requesttask.RequestDoPlayRecordTask;
import com.elinkway.infinitemovies.listener.MyOnAdListener;
import com.elinkway.infinitemovies.listener.NetClarityListener;
import com.elinkway.infinitemovies.listener.PlayCallBackListener;
import com.elinkway.infinitemovies.selfdata.AdRequestStatis;
import com.elinkway.infinitemovies.selfdata.MyDataRecordCreater;
import com.elinkway.infinitemovies.selfdata.SelfDataConstant;
import com.elinkway.infinitemovies.selfdata.bean.MyDataRecord;
import com.elinkway.infinitemovies.selfdata.bean.PlayDataRecord;
import com.elinkway.infinitemovies.selfdata.dao.RealmDaoManager;
import com.elinkway.infinitemovies.ui.activity.LoginActivity;
import com.elinkway.infinitemovies.ui.activity.ReportActivity;
import com.elinkway.infinitemovies.ui.activity.VideoDetailActivity;
import com.elinkway.infinitemovies.utils.CDEManager;
import com.elinkway.infinitemovies.utils.DialogUtil;
import com.elinkway.infinitemovies.utils.LogCat;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.MoviesUtils;
import com.elinkway.infinitemovies.utils.NetWorkTypeUtils;
import com.elinkway.infinitemovies.utils.PlayDataReporter;
import com.elinkway.infinitemovies.utils.RequestSniffDataTaskPoolManager;
import com.elinkway.infinitemovies.utils.SharePreferenceManager;
import com.elinkway.infinitemovies.utils.StringUtil;
import com.elinkway.infinitemovies.utils.ToastUtil;
import com.elinkway.infinitemovies.utils.TrafficStatsUtil;
import com.elinkway.infinitemovies.utils.UIs;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.utils.UmengPostConstant;
import com.elinkway.infinitemovies.utils.UpdateSnifferManager;
import com.elinkway.infinitemovies.utils.Utils;
import com.elinkway.infinitemovies.view.BaiduInterAdView;
import com.elinkway.infinitemovies.view.ClarityPopupWindow;
import com.elinkway.infinitemovies.view.DefinitionManager;
import com.elinkway.infinitemovies.view.GdtNativeAdView;
import com.elinkway.infinitemovies.view.HzPayAdView;
import com.elinkway.infinitemovies.view.ServerNativeAdView;
import com.elinkway.infinitemovies.view.SpacesItemDecoration;
import com.elinkway.infinitemovies.view.TtPayAdView;
import com.elinkway.infinitemovies.view.XfPayAdView;
import com.elinkway.infinitemovies.view.YzPayAdView;
import com.elinkway.infinitemovies.widget.BatteryView;
import com.elinkway.infinitemovies.widget.TimeView;
import com.flyco.tablayout.SlidingTabLayout;
import com.funshion.video.util.FSError;
import com.le123.ysdq.BuildConfig;
import com.le123.ysdq.R;
import com.letv.pp.func.CdeHelper;
import com.letv.pp.service.CdeService;
import com.letv.sdk.callbacks.LetvPlayer;
import com.letv.sdk.callbacks.LetvPlayerView;
import com.lvideo.component.extraplayer.Interface.MyAdStatusListener;
import com.lvideo.component.extraplayer.Interface.OnLetvSdkErrorListener;
import com.lvideo.component.extraplayer.LVideoMediaPlayerControl;
import com.lvideo.component.extraplayer.LVideoVideoViewBuilder;
import com.lvideo.component.extraplayer.utils.MyPlayerConstant;
import com.lvideo.component.extraplayer.videoview.VideoViewBestvProxy;
import com.lvideo.component.extraplayer.videoview.VideoViewFunshionProxy;
import com.lvideo.component.extraplayer.videoview.VideoViewLetvProxy;
import com.lvideo.component.extraplayer.videoview.VideoViewPPTVProxy;
import com.lvideo.component.extraplayer.videoview.VideoViewPasterProxy;
import com.lvideo.component.extraplayer.videoview.VideoViewTencentProxy;
import com.lvideo.http.bean.LVideoDataHull;
import com.novaplayer.LetvMediaPlayerControl;
import com.pplive.sdk.PPTVSdkMgr;
import com.pplive.sdk.PPTVSdkParam;
import com.tencent.qqlive.mediaplayer.api.TVK_PlayerMsg;
import com.tencent.qqlive.mediaplayer.api.TVK_PlayerVideoInfo;
import com.tencent.qqlive.mediaplayer.api.TVK_UserInfo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.concurrent.ExecutionException;

import static com.elinkway.infinitemovies.utils.MoviesConstant.letvPlayStatus;

/**
 * 播放器UI控制层
 *
 * @author zhangshuo
 */
@SuppressLint("NewApi")
public class PlayMediaController implements OnClickListener,
        OnPreparedListener, OnCompletionListener, OnErrorListener,
        OnBufferingUpdateListener, OnInfoListener, OnTouchListener, MyAdStatusListener,
        RequestStreamResultListener<VStreamInfoList>, MediaPlayer.OnVideoSizeChangedListener,OnLetvSdkErrorListener {

    private final String TAG = "PlayMediaController";

    /**
     * 用于请求单集信息的vid
     */
    private String mSingleInfoVid;

    private String mDefaultDefinition = "";

    private String mSnifferUrl = null;

    private String mVideoName = null;

    /**
     * 当前正在播放的Url
     */
    private String mCurrentPlayingUrl = null;

    private String mSnifferParamter = "";

    private String M3U8 = "m3u8";

    private String Mp4 = "mp4";

    private String SNIFF_SUCCESS = "success";

    private String mCurrCloudType = PlayDecodeMananger.getCloudSourceType();

    private String mRule = "";

    private String mCurrSinffType = "";

    /**
     * 默认播放清晰度为标清
     */
    private String mdefaultClarity = PlayerUtils.VIDEO_MP4_350;

    private String mOutsiteClarity = MoviesConstant.SUPER;

    private String mCloudClarity = "";    //用于云盘选择清晰度

    private String PLAY = "0";

    private int mStreamIndex;

    private long mPosition;

    private boolean mIsStartNewPlayerByDrag;

    private boolean mIsLoadAllPiece;

//    private String mPlayUrl = "";

    private String mLinkShellUrl;

    private String mCurrOrder = "";

    /**
     * 最小缓冲时间1秒
     */
    private final int MIN_BUFFER_TIME = 1;

    /**
     * 最大缓冲时间10分钟
     */
    private final int MAX_BUFFER_TIME = 600;

    private final int PAGESIZE = 100;

    private final String NEED_REPORT = "1";

    /**
     * 当前剧集所处的位置
     */
    private int mCurrPage;

    /**
     * 当前的总时长
     */
    private long mDuration;

    /**
     * 加载的当前个数
     */
    private int mTime;

    /**
     * 缓冲时间
     */
    private long mBufferTime = 0;

    /**
     * 播放进度条的最大值
     */
    private final long PLAY_SEEKBAR_MAX = 1000L;

    /**
     * 可以认为是播放成功的最小位置
     */
    private final int PLAY_SUCCESS_POSITION_MIN = 1000;

    private boolean isBigDataInit;

    /**
     * 单集视频
     */
    private final int SINGLE_PERIODS = 1;

    private int mSniffRetryCount = 0;

    /**
     * 当前重试的次数
     */
    private int mReplayNum = 0;

    private final int REPLAY_MAX = 3;

    /**
     * 当前影片在剧集列表中的位置
     */
    private int mVideoPosition = 0;

    /**
     * 当前影片播放位置
     */
    private int mCurrPlayTime = 0;

    private int mCloudPlayPosition = 0;

    private ArrayList<String> mPorderList;

    private ArrayList<String> mStateList;

    private HashMap<String, String> mApiMap;

    private HashMap<String, String> mRuleMap;

    private HashMap<String, String> mPlayUrlMap;

    /**
     * 当前是否为暂停状态
     */
    private boolean mIsPause = false;

    private boolean mIsFirstTime = true; //第一次统计总时间

    /**
     * 当前播放器是否准备完成可以播放影片
     */
    /**
     * zhangshuo 2014年5月7日 下午4:49:51
     */
    public boolean mIsPrepared = false;

    public boolean mIsPlayingAdvertisement = false;

    public int mPlayAdPisition;

    /**
     * 判断当前控制台是否展现
     */
    private boolean mIsControllerShow = false;

    /**
     * 当前播放的是否是本地文件
     */
    private boolean mIsPlayLocalUrl = false;

    private Activity mSelfOwnActivity;

    private LetvMediaPlayerControl mPlayContorl;

    private RelativeLayout mMediaControllerTop;
    private RelativeLayout mDown;// 切换清晰度延时提示
    private TextView mChange_clarity;// 切换清晰度延时

    /**
     * 播放器的外围的容器
     */
    private RelativeLayout mVideoViewPosition;

    private LinearLayout mMediaControllerBottmon;

    private ImageView mCenterPlayIv;

    private View pauseAdLayout;
    private ImageView pauseAdImgIv;
    private ImageView mPauseAdCloseIv;
    private ImageView mPauseAdLogoIv;
    private TextView mPauseAdTipsTv;
    private LayoutParams pauseAdTipsParams;
    private LayoutParams pauseAdLogoFullParams;
    private LayoutParams pauseAdLogoHalfParams;
    private LayoutParams pauseAdFullParams;
    private LayoutParams pauseAdHalfParams;
    private LayoutParams pauseAdImgFullParams;
    private LayoutParams pauseAdImgHalfParams;
    private LayoutParams pauseAdDeleteFullParams;
    private LayoutParams pauseAdDeleteHalfParams;

    private NewAdDataBean mPauseAd;

    private NewAdDataBean mPasterAd;

    private ArrayList<String> mGdtAdPhotoUri;

    private ImageView mSwitchScreenIv;

    private TextView bottomTipsTv;

    /**
     * 播放出错的layout
     */
    private LinearLayout mPlayErrorLayout;

    private LinearLayout mSelectLinearLayout;

    private RelativeLayout mLoadingLayout;

    private LinearLayout mVideoLoadingLl;

    private ImageView playAnimation;

    private PlayData mPlayData;

    /**
     * 播放出错时提示的icon
     */
    private TextView mPlayErrorView;

    /**
     * 快退按钮
     */
//    private ImageView mPlayPreBtn;

    /**
     * 下一集按钮
     */
    private ImageView mPlayNextBtn;

    /**
     * 播放按钮
     */
    private ImageView mPlayBtn;

    /**
     * 锁屏状态按钮
     */
    private ImageButton mLockScreenBtn;

    private TextView mNetRate;

    /**
     * 选集按钮
     */
    private TextView mSelectBtn;

    /**
     * 当前播放时间
     */
    private TextView mCurrTime;

    /**
     * 当前影片总时长
     */
    private TextView mTotalTime;

    /**
     * 用户当前拖动的时间显示在进度条上方
     */
    private TextView mDragCurrTime;

    private ArrayList<Integer> mStreamListTime;

    private TextView mTitile;
    private TextView mTitleWebsite;
    private ImageView mFeedBackButton;
    private View mFeedBackPopView;

    private TimeView mTimeView;
    private BatteryView mBatteryView;
    private LinearLayout mSystemInfoViewLayout;

    private View fullScreenEpisodeView;
    private RecyclerView localEpisodeRv;
    /**
     * 展示集数的ListView
     */

    private EpisodeLocalPlayAdapter mLocalAdapter;

    /**
     * 播放器进度条
     */
    private SeekBar mPlaySeekBar;

    protected PlayerTimer mPlayerTimer;

    private SingleInfo mSingleInfo;

    /**
     * 当前播放影片需要用到数据
     */
    private Episode mPlayEpisode;

    private LVideoVideoViewBuilder mVideoViewBuilder;

    /**
     * 播放需要用到的View
     */
    private View mPlayerView;

    /**
     * 播放广告需要用到的View
     */
    private View mPlayPasterAdView;

    private GdtNativeAdView mGdtNativeAdView;

    private XfPayAdView mXfPayAdView;
    private TtPayAdView mTtPayAdView;

    /**
     * 播放记录
     */

    private PlayRecordDao mPlayRecordDao;

    private UMengReport mUMengReport;

    private ArrayList<Episode> mEpisodes;

    /**
     * 云盘播放地址
     */
    private ArrayList<String> mCloudPlayUrls;
    private ArrayList<String> videoCaseList = new ArrayList<>();

    /**
     * 从下载管理传入的播放列表
     */
    private ArrayList<LocalVideoEpisode> mLocalPlayLists;

    private RequestVStreamListTask mRequestVStreamListTask; // 乐视流

    private RequestCloudDiskTask mRequestCloudTask; // 云盘流

    private RequestCloudErrorTask mRequstCloudErrorTask;

//    private RequestSingleInfoTask mSingleInfoTask; // 外网流

    private android.content.DialogInterface.OnClickListener mDialogOnClickListener;

    private OnKeyListener mDialogOnKeyListener;

    private Window mWindow;

    private Animation mLockScreenAni;

    /**
     * 相关手势操作
     */
    protected VideoPlayerGestureHandle mGestureHandle;
    /**
     * 是否是通过手势操作调节音量
     */
    private boolean mSystemHardKeyAdjustVolume = false;

    private AudioManager mAudioManager;
    /**
     * 系统最大和最小音量
     */
    private final int VOLUME_UNINIT = -1;
    private final int VOLUME_MIN = 0;
    private static int VOLUME_MAX = 1500;
    /**
     * 是否静音
     */
    private boolean mIsSilent = false;

    /**
     * 系统当前的声音值
     */
    private int mCurrentVolume = VOLUME_UNINIT;

    private RelativeLayout mMediaController;
    /**
     * 清晰度
     */
    private TextView mClarity_select;
    private ClarityPopupWindow mClarityPopupWindow;
    /**
     * 清晰度码流--默认为标清
     */
    private String lvideoVideoCode = PlayerUtils.PLS_MP4_350;

    /**
     * 存储各种清晰度是否可用
     */
    private Map<String, Boolean> mClaritymap;
    /**
     * 切换清晰度后，需要执行seek操作
     */
    private boolean mIsNeedSeekByClarity = false;
    /**
     * 缓冲10秒提示动画
     */
    private Animation mShowChangeAnimation;
    private Animation mDissMissChangeAnimation;

    private WebView mWebView;

    private TestJavaScriptInterface mTestInterface;

    private PlayState mCurrPlayState;

    /**
     * 大数据上报
     */
    private BigDataPlayReporter bigDataPlayReporter;

    /**
     * 播放数据上报(自己的服务器)
     */
    private PlayDataReporter mPlayDataReport = new PlayDataReporter();
    private PlayDataReporter.PlayPeriod mPlayPeriod;
    private PlayDataReporter.PlayBuffer mPlayBuffer;
    private PlayStatusReporter mPlayStatusReport = new PlayStatusReporter();
    private String mReportAid = "";

    private CDEManager mCDEManager;

    private CDEStatusReceiver mCdeStatusReiver;

    private Handler mPlayTimeHandler; // 心跳上报
    private int pt;// 心跳时间 [1,180]
    public static int FIRST_TIME = 15 * 1000;
    public static int SECOND_TIME = 75 * 1000;
    public static int INTERVAL_TIME = 180 * 1000;
    public static int INTERVAL_TIME_CLOUD = 60 * 1000;

    private boolean isFirstReport;
    private boolean isSecondReport;

    private long play_start;
    private long play_time;
    protected PlayerTimer mThirdReportTimer;

    private boolean isCloud;

    //新外网截流 start
    private RequestOutSiteStreamInfoTask mOutSiteStreamInfoTask;
    private UpLoadLocalStreamTask mUpLoadLocalStreamTask;
    private UpdatestreamTask mUpdatestreamTask;
    private OutSiteStreamInfo mOutSiteStreamInfo;
    private List<OutSiteStreamEntity> mStreamEntityList;
    private OutSiteStreamEntity mOutSiteStreamEntity;
    private boolean isNeedRetry; //再次请求流数据
    private int retryTime; //重试次数1次
    private List<String> mAllowFormats;
    private String mRequestFormat;
    private String mOsType;
    private String mEid;
    private String mIsDownload;
    private List<String> mStream_list;
    private List<String> mApi_list;
    private List<String> mApi_contentlist;
    private boolean isSpecialSniff;
    private String mUser_agent;
    private boolean isHasRule;
    private Map<String, String> mJsRuleMap;
    private String mTe;
    private String mTs;
    private int mCurStreamIndex;
    private boolean isNeedJsCut; // 是否需要本地截流
    private boolean isQuitSniff; // 截流成功与否

    private static String TE = "te";
    private static String TS = "ts";
    private static String OSTYPE_M3U8 = "IOS";
    private static String OSTYPE_MP4 = "ANDROID";

    // 流地址失败状态码 end
    private static final int PLAY_FAIL = 0;
    private static final int DURATION_ERROR = 1;
    private static final int NO_STREAM = 2;
    private static final int UNKNOWN_ERROR = 3;

    private int mInSiteRetryTime; // 乐视源，网盘源数据请求失败重试次数
    private long mBlockTime;// 缓冲时间（block-eblock）
    private SharedPreferences mLoginSP;
    private SharedPreferences mClaritySp;

    private ImageView mShowDeviceIv;

    private String bottomTips;
    private View forScreenLay;
    private TextView tvNameTv;
    private TextView exitForScreenTv;
    private boolean isNeedShowNext = true;
    private boolean isNeedShowSelect = true;
    private boolean mIsFirstTimeFullScreen = true;
    private boolean mIsFullScreen;
    private View mPlayPositionView;
    private PopupWindow mPopupWindow;
    private ImageView mImgBack;

    //用于双击屏幕计数
    private int count;
    private long firClick;
    private long secClick;

    private int mCurrentStep = 0;
    private long mTimeMillis = 0;
    private static final int FIRST_STEP = 1;
    private static final int SECOND_STEP = 2;
    private static final int OTHER_STEP = 3;
    private static final int ONE_SECOND = 1000;
    private static final int FIRST_STEP_TIME = 15 * ONE_SECOND;
    private static final int SECOND_STEP_TIME = 60 * ONE_SECOND;
    private static final int OTHER_STEP_TIME = 180 * ONE_SECOND;
    private List<Integer> mSohuDefinitionList = null;
    private boolean isInPlayingProcess = false;     //是否在播放过程中，用于block和eblock的统计

    private boolean mPptvInit = false;

    private boolean mPlayAd = false;

    private LetvPlayer mLetvPlayer; // 乐视player统计用
    private boolean mHasSetFullScreen = false;

    protected AnimationDrawable loadingAnimationDrawable;

    private SlidingTabLayout mFullTabs;

    private ViewPager mFullViewPager;

    private EpisodePagerAdapter mFullEpisodePagerAdapter;

    private boolean isFirstDragReported = false; //用于判断两次drag上报

    private LinearLayout attachAdLinearLayout;

    private TextView attachAdSecond;

    private TextView attachAdSkip;

    private RelativeLayout attachAdBottomLinearLayout;

    private ImageView sound;

    private TextView seeDetails;

    private ImageView adSwitchScreen;

    private int adSecond;

    private boolean soundClose = false;

    private boolean ischangeClarity = false;    //判断切清晰度情况下不请求贴片广告

    public LinearLayout mRetryLinearLayout;

    private RelativeLayout mRetryButton;

    private TextView mPlayerStatus;

    private TextView mPlayerStatusImage;

    private TextView mPlayInWeb;

    private LinearLayout mPlayStatus;

    private long mRealPlayTime = 0;
    private HashMap<String, String> mRealPlayMap = new HashMap<>();
    private boolean mIsJSFailed;

    private boolean mIsJSSuccessed;

    private boolean mIsAllowLetvSdk = true;

    private boolean mIsBuffering = false;   //视频播放过程中是否处于缓冲
    private LetvPlayerView mLetvView;
    private RequestAdTask mRequestAdTask;

    private String mAttachAdType;

    private boolean mIsSdkPlayer;
    private ImageView mBatteryLightningView;

    public PlayMediaController(Activity selfOwnActivity, View playerView) {
        mSelfOwnActivity = selfOwnActivity;
        mVideoViewBuilder = LVideoVideoViewBuilder.getInstants();
        mClaritySp = mSelfOwnActivity.getSharedPreferences(SettingManage.SETTING_RELATIVE_SHAREPREFERENCE, Context.MODE_PRIVATE);
        mOutsiteClarity = mClaritySp.getString(MoviesConstant.DOWNLOAD_SHARPNESS_SELECT, MoviesConstant.SUPER);
        mPlayPositionView = playerView;
        initView();
        initData();
        setListener();
        initAudioVolume();
        bigDataPlayReporter = new BigDataPlayReporter();
        bigDataPlayReporter.setNt(BigDataUtils.getNetType(mSelfOwnActivity));
        mLoginSP = mSelfOwnActivity.getSharedPreferences(SettingManage.LOGIN_INFO, Context.MODE_PRIVATE);

        IntentFilter javaFilter = new IntentFilter();
        javaFilter.addAction("android.intent.action.TIME_TICK");
        mSelfOwnActivity.registerReceiver(timeReceiver, javaFilter);
        mSelfOwnActivity.registerReceiver(batteryChangedReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }

    public void setPlayMediaControlView(View view) {
        mPlayPositionView = view;
    }

    @SuppressLint("SetJavaScriptEnabled")
    public void initWebView(Activity activity) {
        setConfigCallback((WindowManager) activity.getApplicationContext().getSystemService(Context.WINDOW_SERVICE));
        mWebView = new WebView(activity.getApplicationContext());
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setAppCacheEnabled(false);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.clearCache(true);
        String htmlUrl = UpdateSnifferManager.getInstance().getHtmlURL();
        LogCat.e(Utils.TAG, " js file get from " + htmlUrl);
        mWebView.loadUrl(htmlUrl);
        mWebView.addJavascriptInterface(mTestInterface, "TestJavaScriptInterface");
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogUtils.d(Utils.TAG, " url:" + url);
//                view.loadUrl(url);// 当打开新链接时，使用当前的 WebView，不会使用系统其他浏览器
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                setIsLoaded(true);
                LogUtils.e(Utils.TAG, "  js webview loaded ok");
                // mWebView.loadUrl(htmlUrl);
            }

        });
    }

    boolean isWebLoaded = false;

    void setIsLoaded(boolean isLoad) {
        this.isWebLoaded = isLoad;
    }

    private void initView() {
        mPlayStatus = (LinearLayout)mSelfOwnActivity.findViewById(R.id.ll_play_status);
        mRetryLinearLayout = (LinearLayout)mSelfOwnActivity.findViewById(R.id.ll_retry);
        mPlayerStatusImage = (TextView) mSelfOwnActivity.findViewById(R.id.iv_status);
        mPlayerStatus = (TextView) mSelfOwnActivity.findViewById(R.id.tv_video_description);
        mRetryButton = (RelativeLayout) mSelfOwnActivity.findViewById(R.id.rl_retry_button);
        mPlayInWeb = (TextView) mSelfOwnActivity.findViewById(R.id.tv_play_web);
        setRetryListener();
        mCenterPlayIv = (ImageView) mSelfOwnActivity.findViewById(R.id.center_play_iv);

        pauseAdLayout = mSelfOwnActivity.findViewById(R.id.pause_ad_layout);
        pauseAdFullParams = new LayoutParams(UIs.dipToPx(331), UIs.dipToPx(197));
        pauseAdFullParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        pauseAdHalfParams = new LayoutParams(UIs.dipToPx(205), UIs.dipToPx(123));
        pauseAdHalfParams.addRule(RelativeLayout.CENTER_IN_PARENT);

        pauseAdImgIv = (ImageView) mSelfOwnActivity.findViewById(R.id.pause_ad_image);
        pauseAdImgFullParams = new LayoutParams(UIs.dipToPx(305), UIs.dipToPx(171));
        pauseAdImgFullParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        pauseAdImgHalfParams = new LayoutParams(UIs.dipToPx(187), UIs.dipToPx(105));
        pauseAdImgHalfParams.addRule(RelativeLayout.CENTER_IN_PARENT);

        mPauseAdCloseIv = (ImageView) mSelfOwnActivity.findViewById(R.id.ad_close_iv);
        pauseAdDeleteFullParams = new LayoutParams(UIs.dipToPx(26), UIs.dipToPx(26));
        pauseAdDeleteFullParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        pauseAdDeleteHalfParams = new LayoutParams(UIs.dipToPx(18), UIs.dipToPx(18));
        pauseAdDeleteHalfParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

        mPauseAdTipsTv = (TextView) mSelfOwnActivity.findViewById(R.id.ad_tips_tv);
        mPauseAdLogoIv = (ImageView) mSelfOwnActivity.findViewById(R.id.ad_logo_iv);
        pauseAdTipsParams = (LayoutParams) mPauseAdTipsTv.getLayoutParams();
        pauseAdTipsParams.addRule(RelativeLayout.ALIGN_TOP, R.id.ad_logo_iv);
        pauseAdLogoFullParams = new LayoutParams(UIs.dipToPx(19), UIs.dipToPx(15));
        pauseAdLogoFullParams.addRule(RelativeLayout.ALIGN_LEFT, R.id.pause_ad_image);
        pauseAdLogoFullParams.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.pause_ad_image);
        pauseAdLogoFullParams.leftMargin = UIs.dipToPx(2);
        pauseAdLogoFullParams.bottomMargin = UIs.dipToPx(2);
        pauseAdLogoHalfParams = new LayoutParams(UIs.dipToPx(16), UIs.dipToPx(13));
        pauseAdLogoHalfParams.addRule(RelativeLayout.ALIGN_LEFT, R.id.pause_ad_image);
        pauseAdLogoHalfParams.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.pause_ad_image);
        pauseAdLogoHalfParams.leftMargin = UIs.dipToPx(2);
        pauseAdLogoHalfParams.bottomMargin = UIs.dipToPx(2);

        mSwitchScreenIv = (ImageView) mSelfOwnActivity.findViewById(R.id.switch_screen_iv);

        mSelectBtn = (TextView) mSelfOwnActivity.findViewById(R.id.episode_select_tv);
        mSelectLinearLayout = (LinearLayout) mSelfOwnActivity.findViewById(R.id.select_layout);

        fullScreenEpisodeView = mSelfOwnActivity.findViewById(R.id.fullscreen_episode_page);
        localEpisodeRv = (RecyclerView) mSelfOwnActivity.findViewById(R.id.episode_local_grid_view);
        mFullTabs = (SlidingTabLayout) fullScreenEpisodeView.findViewById(R.id.fullscreen_episode_page_tabs);
        mFullViewPager = (ViewPager) fullScreenEpisodeView.findViewById(R.id.fullscreen_episode_pager);

        mLockScreenBtn = (ImageButton) mSelfOwnActivity.findViewById(R.id.videoplayer_lockscreen);
        setLockScreenVisibile(false);
        mVideoViewPosition = (RelativeLayout) mSelfOwnActivity.findViewById(R.id.videoview_position);

        mPlaySeekBar = (SeekBar) mSelfOwnActivity.findViewById(R.id.full_play_seekbar);
        mPlaySeekBar.setMax((int) PLAY_SEEKBAR_MAX);
        mPlaySeekBar.setProgress(0);
        mPlaySeekBar.setSecondaryProgress(0);

        mPlayNextBtn = (ImageView) mSelfOwnActivity.findViewById(R.id.btn_play_next);
        mPlayBtn = (ImageView) mSelfOwnActivity.findViewById(R.id.btn_play);
        mPlayErrorView = (TextView) mSelfOwnActivity.findViewById(R.id.videoplayer_error_icon);

        mTitile = (TextView) mSelfOwnActivity.findViewById(R.id.tv_video_title);

        mFeedBackButton = (ImageView) mSelfOwnActivity.findViewById(R.id.iv_feedback);
        mTimeView = (TimeView) mSelfOwnActivity.findViewById(R.id.time_view);
        mBatteryView = (BatteryView) mSelfOwnActivity.findViewById(R.id.battery_view);

        mSystemInfoViewLayout = (LinearLayout) mSelfOwnActivity.findViewById(R.id.system_info);
        mImgBack = (ImageView) mSelfOwnActivity.findViewById(R.id.video_player_playback_btn);

        attachAdLinearLayout = (LinearLayout) mSelfOwnActivity.findViewById(R.id.ll_attach_ad);
        attachAdBottomLinearLayout = (RelativeLayout) mSelfOwnActivity.findViewById(R.id.ll_bottom_attach_ad);
        sound = (ImageView) mSelfOwnActivity.findViewById(R.id.iv_attach_ad_sound);
        adSwitchScreen = (ImageView) mSelfOwnActivity.findViewById(R.id.iv_ad_switch_screen);
        seeDetails = (TextView) mSelfOwnActivity.findViewById(R.id.iv_ad_see_details);
        attachAdSecond = (TextView) mSelfOwnActivity.findViewById(R.id.tv_attach_ad_second);
        attachAdSkip = (TextView) mSelfOwnActivity.findViewById(R.id.tv_attach_ad_skip);

        if (!NEED_REPORT.equals(PreferencesManager.getInstance().getReport())) {
            mFeedBackButton.setVisibility(View.GONE);
        }

        mFeedBackButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mPopupWindow.isShowing()) {
                    mPopupWindow.dismiss();

                } else {
                    showPopWindow(mFeedBackButton);
                }
                mFeedBackButton.setClickable(false);
                mFeedBackButton.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        mFeedBackButton.setClickable(true);
                    }

                }, 2000);
            }

        });

        initFeedBackPopWindow();

        mTitleWebsite = (TextView) mSelfOwnActivity.findViewById(R.id.tv_video_website);

        mDragCurrTime = (TextView) mSelfOwnActivity.findViewById(R.id.videoplayer_user_drag_time);
        mCurrTime = (TextView) mSelfOwnActivity.findViewById(R.id.tv_currtime);
        mTotalTime = (TextView) mSelfOwnActivity.findViewById(R.id.tv_totaltime);

        mLoadingLayout = (RelativeLayout) mSelfOwnActivity.findViewById(R.id.layout_loading);
        mNetRate = (TextView) mSelfOwnActivity.findViewById(R.id.loading_net_rate);
        mVideoLoadingLl = (LinearLayout) mSelfOwnActivity.findViewById(R.id.video_loading_ll);
        playAnimation = (ImageView) mSelfOwnActivity.findViewById(R.id.loading_animation);
        mMediaControllerTop = (RelativeLayout) mSelfOwnActivity.findViewById(R.id.mediacontroller_top);
        mDown = (RelativeLayout) mSelfOwnActivity.findViewById(R.id.down);
        mChange_clarity = (TextView) mSelfOwnActivity.findViewById(R.id.change_clarity);
        mMediaControllerBottmon = (LinearLayout) mSelfOwnActivity.findViewById(R.id.layout_mediacontroller_bottom);

        bottomTipsTv = (TextView) mSelfOwnActivity.findViewById(R.id.bottom_tip_tv);

        mPlayErrorLayout = (LinearLayout) mSelfOwnActivity.findViewById(R.id.videoplayer_error_layout);
        mMediaController = (RelativeLayout) mSelfOwnActivity.findViewById(R.id.video_player_control);
        mClarity_select = (TextView) mSelfOwnActivity.findViewById(R.id.clarity_select_tv);
        mClarityPopupWindow = new ClarityPopupWindow(mSelfOwnActivity, mMediaController, changeClarityListener);

        setControllerUI();

        if (null == mGestureHandle) {
            mGestureHandle = new VideoPlayerGestureHandle(mSelfOwnActivity, mHandler, this, mPlayPositionView);
        }
        mTestInterface = new TestJavaScriptInterface();
        initWebView(mSelfOwnActivity);

        mShowDeviceIv = (ImageView) mSelfOwnActivity.findViewById(R.id.show_device_iv);
        forScreenLay = mSelfOwnActivity.findViewById(R.id.for_screen_layout);
        tvNameTv = (TextView) mSelfOwnActivity.findViewById(R.id.for_screen_name_tv);
        exitForScreenTv = (TextView) mSelfOwnActivity.findViewById(R.id.out_screen_tv);
        mBatteryLightningView = (ImageView) mSelfOwnActivity.findViewById(R.id.battery_lightning);
    }

    public void setRetryListener() {
        if (!(mSelfOwnActivity instanceof VideoDetailActivity)) {
            return;
        }
        mRetryButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                PlayDataRecord record = MyDataRecordCreater.build(PlayDataRecord.class);
                record.setAcode(SelfDataConstant.AC_CLICK);
                record.setPlayac(SelfDataConstant.PLAYAC_RETRY);
                record.setCur_url("half_screen");
                if (mPlayData != null) {
                    record.setSite(mPlayData.getSite());
                }
                RealmDaoManager.addMyDataRecord(record);
                Episode episode = null;
                if(mVideoPosition < mEpisodes.size()){
                    episode = mEpisodes.get(mVideoPosition);
                }
                if (episode != null) {
                    executeCommonPlay(episode);
                    int position = mVideoPosition;
                    mVideoPosition = -1;
                    PlayEpisode(position, false);
                } else {
                    requestOutSiteStreamInfo(null);
                }
            }
        });

        mPlayInWeb.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelfOwnActivity instanceof VideoDetailActivity) {
                    PlayDataRecord record = MyDataRecordCreater.build(PlayDataRecord.class);
                    record.setAcode(SelfDataConstant.AC_CLICK);
                    record.setPlayac(SelfDataConstant.PLAYAC_H5_RETRY);
                    record.setCur_url("half_screen");
                    if (mPlayData != null) {
                        record.setSite(mPlayData.getSite());
                    }
                    RealmDaoManager.addMyDataRecord(record);
                    ((VideoDetailActivity)mSelfOwnActivity).jumpToWebViewPlay(mVideoPosition);
                }
            }
        });
    }

    /**
     * UI zhangshuo 2014年5月9日 下午5:11:56
     */
    public void setControllerUI() {
        // 加载影片时不显示底部控制栏
        setMediaControllerBottomVisibile(false);
        showVideoPrepareing();
        setMediaControllerTopVisibile(true);
        setPlayErrorLayoutVisibile(false);
        // 切换选集上下集时更新播放暂停按钮
        updatePlayBtnBg(false);
        if (null != mPlaySeekBar) {
            mPlaySeekBar.setProgress(0);
            mPlaySeekBar.setSecondaryProgress(0);
        }
    }

    private void showVideoPrepareing(){
        mLoadingLayout.setVisibility(View.VISIBLE);
        mVideoLoadingLl.setVisibility(View.VISIBLE);
        AnimationDrawable animationDrawable = (AnimationDrawable) playAnimation.getDrawable();
        animationDrawable.start();
        mNetRate.setText(MoviesApplication.getInstance().getString(R.string.will_loading_tip));
    }

    private void showVideoLoading(){
        mVideoLoadingLl.setVisibility(View.VISIBLE);
    }

    /**
     * 初始化数据 zhangshuo 2014年5月4日 上午10:01:48
     */
    private void initData() {
        mCDEManager = CDEManager.getInstance(MoviesApplication.getInstance());
        // 获取当前默认播放的清晰度
        mDefaultDefinition = PlayerUtils.getPlayDefinition();
        LogCat.e(TAG, "!!!!当前默认的清晰度为!!!!!" + mDefaultDefinition);
        mLockScreenAni = makeBlinkAnimation(mSelfOwnActivity);
        mUMengReport = new UMengReport();
        mPlayRecordDao = new PlayRecordDao(MoviesApplication.getInstance());
        mRequestVStreamListTask = new RequestVStreamListTask(MoviesApplication.getInstance());
        mDialogOnClickListener = new ExitDialogOnClickListener();
        mDialogOnKeyListener = new ExitOnKeyListener();

        if (Utils.getAPILevel() >= PlayerUtils.API_14) {
            // 设置虚拟键显示和隐藏的监听
            mWindow = mSelfOwnActivity.getWindow();
            // 设置当前屏幕不锁屏
            mWindow.setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
        mClaritymap = new HashMap<>();
        mShowChangeAnimation = AnimationUtils.loadAnimation(mSelfOwnActivity, R.anim.change_clarity_show);
        mDissMissChangeAnimation = AnimationUtils.loadAnimation(mSelfOwnActivity, R.anim.change_clarity_dissmiss);
        mPlayTimeHandler = new Handler();
    }

    public void initFeedBackPopWindow() {
        mFeedBackPopView = UIs.inflate(mSelfOwnActivity, R.layout.feedback_pop_layout, null);
        TranslateAnimation animTopIn = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                0.0f, Animation.RELATIVE_TO_SELF, -0.5f,
                Animation.RELATIVE_TO_SELF, 0.0f);
        animTopIn.setDuration(300);
        mFeedBackPopView.setAnimation(animTopIn);
        mFeedBackPopView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mSelfOwnActivity, ReportActivity.class);
                intent.putExtra("aid", mReportAid);
                intent.putExtra("site", mPlayData.getSite());
                mSelfOwnActivity.startActivity(intent);
            }
        });
        mPopupWindow = new PopupWindow(mFeedBackPopView,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setFocusable(false);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mFeedBackPopView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mFeedBackPopView.setClickable(true);
                    }
                }, 200);
            }
        });
    }

    public void showPopWindow(View view) {
        if (mPopupWindow == null) {
            return;
        }
        mPopupWindow.setAnimationStyle(R.style.popwin_anim_style);
        if (!mSelfOwnActivity.isFinishing()) {
            mPopupWindow.showAsDropDown(view, UIs.dipToPx(-35), 0);
        }
    }

    /**
     * 设置监听器对象 zhangshuo 2014年4月27日 下午8:56:39
     */
    private void setListener() {
        mSwitchScreenIv.setOnClickListener(this);
        mSelectBtn.setOnClickListener(this);
        mPlayErrorView.setOnClickListener(this);
        mLockScreenBtn.setOnClickListener(this);
        mPlayNextBtn.setOnClickListener(this);
        mPlayBtn.setOnClickListener(this);
        mCenterPlayIv.setOnClickListener(this);
        mPlaySeekBar.setOnSeekBarChangeListener(mPlaySeekBarChangeListener);
        mPlaySeekBar.setOnTouchListener(this);
        mRequestVStreamListTask.setListener(this);
        mMediaControllerTop.setOnTouchListener(this);
        mMediaControllerBottmon.setOnTouchListener(this);
        mClarity_select.setOnClickListener(this);
        mChange_clarity.setOnClickListener(this);
        mShowDeviceIv.setOnClickListener(this);
    }

    private void setPlayerListener() {
        mPlayContorl.setOnPreparedListener(this);
        mPlayContorl.setOnCompletionListener(this);
        mPlayContorl.setOnBufferingUpdateListener(this);
        mPlayContorl.setOnErrorListener(this);
        mPlayContorl.setOnInfoListener(this);
        if (mPlayContorl instanceof LVideoMediaPlayerControl) {
            ((LVideoMediaPlayerControl) mPlayContorl).setOnAdListener(this);
        }
        mPlayContorl.setOnSeekCompleteListener(mPlaySeekCompleteListener);
        mVideoViewPosition.setOnTouchListener(this);
    }

    private void setAttachAdListener() {
        sound.setOnClickListener(this);
        adSwitchScreen.setOnClickListener(this);
        attachAdSkip.setOnClickListener(this);
        mPlayPasterAdView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mPasterAd != null && "10".equals(mPasterAd.provider)) {
                    if ("1".equals(((HzPayload)mPasterAd.payload).ad.action)) {
                        CommonAdActionHandle.getInstance().go2WebView(mSelfOwnActivity, ((HzPayload) mPasterAd.payload).ad.url);
                        HashMap<String, String> gdtPropertyMap = new HashMap<>();
                        if (mPlayData != null) {
                            gdtPropertyMap.put("source", mPlayData.getSite());
                        }
                        gdtPropertyMap.put("ad_type", "h5");
                        UmengEventPoster.doPost(UmengEventPoster.HZPEROLLS_CLICK, gdtPropertyMap);
                    } else {
                        HzAdBean hzAdBean = ((HzPayload) mPasterAd.payload).ad;
                        CommonAdActionHandle.getInstance().downloadApp(mSelfOwnActivity, hzAdBean.app.name, hzAdBean.app.name, hzAdBean.app.icon_url, hzAdBean.url,
                                hzAdBean.dp_url, hzAdBean.download_urls, hzAdBean.downloaded_urls, hzAdBean.installed_urls);
                        HashMap<String, String> gdtPropertyMap = new HashMap<>();
                        if (mPlayData != null) {
                            gdtPropertyMap.put("source", mPlayData.getSite());
                        }
                        gdtPropertyMap.put("ad_type", "download");
                        UmengEventPoster.doPost(UmengEventPoster.HZPEROLLS_CLICK, gdtPropertyMap);
                    }
                    ArrayList<String> adClickReportUrls = ((HzPayload)mPasterAd.payload).ad.clk;
                    if(adClickReportUrls != null && adClickReportUrls.size() > 0){
                        for (int i=0;i<adClickReportUrls.size();i++){
                            if(!TextUtils.isEmpty(adClickReportUrls.get(i))){
                                new ThirdAdReportTask(MoviesApplication.getInstance(), adClickReportUrls.get(i)).start();
                            }
                        }
                    }
                }
                return false;
            }
        });
    }

    private void setPlayLoadingVisibile(boolean flag) {
        if (null != mLoadingLayout) {
            if (flag) {
                if (!mLoadingLayout.isShown()) {
                    // 显示
                    if(mGestureHandle != null && mGestureHandle.isGesturePopupWindowShow()){
                        return;
                    }
                    mLoadingLayout.setVisibility(View.VISIBLE);
                    AnimationDrawable animationDrawable = (AnimationDrawable) playAnimation.getDrawable();
                    animationDrawable.start();
                    showNetRate();
                    mBlockTime = System.currentTimeMillis();
                    LogCat.e(TAG, "!!!!!!!!!!!!!!block!!!!!!!!!!!!!!");
                    if (bigDataPlayReporter != null && isBigDataInit && isInPlayingProcess) {
                        bigDataPlayReporter.setAc(BigDataConstants.PLAY_AC_BLOCK);
                        bigDataPlayReporter.onPlayProcess();
                        reporterTime();
                    }
                    if (mSelfOwnActivity != null) {
                        // wuxinrong modified begin
                        int netType = NetWorkTypeUtils.getNetType();
                        if (NetWorkTypeUtils.NETTYPE_NO == netType) {
                            mLoadingLayout.setVisibility(View.INVISIBLE);
                            setPlayErrorLayoutVisibile(true);
                        }
                    }
                }
            } else {
                if (mLoadingLayout.isShown()) {
                    // 不显示
                    mLoadingLayout.setVisibility(View.GONE);
                    AnimationDrawable animationDrawable = (AnimationDrawable) playAnimation.getDrawable();
                    animationDrawable.start();
                    LogCat.e(TAG, "!!!!!!!!!!!!!!blockBufferTime is " + (System.currentTimeMillis() - mBlockTime));
                    LogCat.e(TAG, "!!!!!!!!!!!!!!eblock!!!!!!!!!!!!!!");
                    if (bigDataPlayReporter != null && isInPlayingProcess) {
                        bigDataPlayReporter.setAc(BigDataConstants.PLAY_AC_EBLOCK);
                        bigDataPlayReporter.onPlayProcess();
                        reporterTime();
                    }
                    isInPlayingProcess = true;
                }
            }
        }
    }

    private void setMediaControllerTopVisibile(boolean flag) {
        if (null != mMediaControllerTop) {
            if (flag) {
                if (mIsFullScreen) {
                    statusBarShow(true);
                }
                mMediaControllerTop.setVisibility(View.VISIBLE);
            } else {
                mMediaControllerTop.setVisibility(View.GONE);
                setChangeClarityVisibile(false);
            }
        }
    }

    public void statusBarShow(boolean enable) {
        Window window = mSelfOwnActivity.getWindow();
        if (enable) {
            WindowManager.LayoutParams attr = window.getAttributes();
            attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            window.setAttributes(attr);
        } else {
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            window.setAttributes(lp);
        }
    }

    private void setMediaControllerBottomVisibile(boolean flag) {
        if (null != mMediaControllerBottmon) {
            if (flag) {
                mMediaControllerBottmon.setVisibility(View.VISIBLE);
            } else {
                mMediaControllerBottmon.setVisibility(View.GONE);
                if (bottomTipsTv != null && bottomTipsTv.getVisibility() == View.VISIBLE) {
                    bottomTipsTv.setVisibility(View.GONE);
                }
            }
        }
    }

    private void setChangeClarityVisibile(boolean flag) {
        if (null != mMediaControllerTop && null != mDown) {
            if (flag) {
                mDown.setVisibility(View.VISIBLE);
                mDown.startAnimation(mShowChangeAnimation);
            } else {
                mDown.startAnimation(mDissMissChangeAnimation);
                mDissMissChangeAnimation
                        .setAnimationListener(new AnimationListener() {

                            @Override
                            public void onAnimationStart(Animation animation) {

                            }

                            @Override
                            public void onAnimationRepeat(Animation animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animation animation) {
                                mDown.setVisibility(View.GONE);
                            }
                        });
            }
        }
    }

    public void setmPlayData(PlayData mPlayData, boolean isPlay, boolean isFirstEnterVideoDetail) {
        if (null != mPlayData) {
            if (!TextUtils.isEmpty(mPlayData.getAid())) {
                mReportAid = mPlayData.getAid();
                bigDataPlayReporter.setPid(mPlayData.getAid()).setVid(mPlayData.getAid());
            } else {
                bigDataPlayReporter.setPid("-").setVid("-");
            }
            if (!TextUtils.isEmpty(mPlayData.getCategory())) {
                bigDataPlayReporter.setCid(mPlayData.getCategory());
            } else {
                bigDataPlayReporter.setCid("-");
            }
            if (!TextUtils.isEmpty(mPlayData.getThemeId())) {
                bigDataPlayReporter.setZid(mPlayData.getThemeId());
            } else {
                bigDataPlayReporter.setZid("-");
            }
            mPlayDataReport.setAid(mPlayData.getAid());
        }

        mIsPlayingAdvertisement = false;
        this.mPlayData = mPlayData;
        String porder = mPlayData.getPorder();
        if (null != mPlayData) {

            mIsPlayLocalUrl = mPlayData.getIsLocalVideo();
            int size = 0;
            isFirstDragReported = false;
            // 当前播放的是本地文件
            if (mIsPlayLocalUrl) {
                bigDataPlayReporter.setPlayType(BigDataConstants.TY_LOCAL);
                mLocalPlayLists = mPlayData.getmLocalDataLists();
                if (null != mLocalPlayLists && mLocalPlayLists.size() > 0
                        && !TextUtils.isEmpty(porder)) {
                    size = mLocalPlayLists.size();
                    LocalVideoEpisode localVideoEpisode = getCurrLocalEisode(porder);
                    executeLocalPlayLogic(localVideoEpisode);
                    if(mLocalPlayLists.get(0) != null){
                        this.mPlayData.setVt(mLocalPlayLists.get(0).getVt());
                    }
                    if (MoviesConstant.VT_MOVIE.equals(this.mPlayData.getVt())) {
                        setSelectVisibile(false);
                        setNextBtnVisibile(false);
                    } else {
                        setSelectVisibile(false);
                        setSelectClickable(true);
                        localEpisodeRv.setVisibility(View.VISIBLE);
                        localEpisodeRv.addItemDecoration(new SpacesItemDecoration(UIs.dipToPx(5)), -1);
                        fullScreenEpisodeView.setVisibility(View.GONE);
                        if (isEpisodeGridview(mLocalPlayLists.get(0).getVt())) {
                            GridLayoutManager mgr = new GridLayoutManager(mSelfOwnActivity, 5);
                            localEpisodeRv.setLayoutManager(mgr);
                            mLocalAdapter = new EpisodeLocalPlayAdapter(mSelfOwnActivity, mLocalPlayLists, "grid");
                        } else {
                            LinearLayoutManager mll = new LinearLayoutManager(mSelfOwnActivity);
                            localEpisodeRv.setLayoutManager(mll);
                            mLocalAdapter = new EpisodeLocalPlayAdapter(mSelfOwnActivity, mLocalPlayLists, "list");
                        }
                        mLocalAdapter.setmSelectProder(mLocalPlayLists.get(mVideoPosition).getPorder());
                        mLocalAdapter.setOnItemClickListener(new SelectPeriodsItemClickListener());
                        localEpisodeRv.setAdapter(mLocalAdapter);
                    }
                }
            } else {
                bigDataPlayReporter.setPlayType(BigDataConstants.TY_ONLINE);
                mPorderList = mPlayData.getmPorderLists();
                mEpisodes = mPlayData.getEpisodes();
                // mPorderList中包含当前所有剧集的porder
                if (null != mPorderList && mPorderList.size() > 0) {
//                    mShowDeviceIv.setVisibility(View.VISIBLE);
                    size = mPorderList.size();

                    if (MoviesConstant.VT_MOVIE.equals(mPlayData.getVt())) {
                        setSelectVisibile(false);
                        setNextBtnVisibile(false);
                    } else {
                        setSelectVisibile(false);
                        setSelectClickable(true);
                    }
                    // 获取当前剧集在播放列表中的位置
                    int prePosition = mVideoPosition;
                    mVideoPosition = getCurrEpisodePosition(porder);
                    // 获取当前集所处的页数
                    mCurrPage = getCurrPage(mVideoPosition);
                    // mEpisodes不为空则为从详情页面进入
                    if (null != mEpisodes && mEpisodes.size() > 0) {
                        // 查找到指定的Episode
                        Episode episode = findEpisodeByPorder(porder);

                        mPlayDataReport = new PlayDataReporter();
                        if (isPlay || (mVideoViewPosition != null && mVideoViewPosition.getVisibility() == View.GONE)) {
                            if (!isFirstEnterVideoDetail) {
                                if (MoviesConstant.VT_ZONGYI.equals(mPlayData.getVt())) {
                                    bottomTips = "第 " + episode.getPorder() + " 期";
                                } else {
                                    bottomTips = "第 " + episode.getPorder() + " 集";
                                }
                            }
                            ischangeClarity = false;
                            mIsAllowLetvSdk = true;
                            executeCommonPlay(episode);
                        } else {
                            mVideoPosition = prePosition;
                        }
                        setSelectListData();
                    } else {
                        // 执行分页数据请求
                    }
                }

            }
            setNextState(size);
        }
    }

    public void updatePlayData(ArrayList<Episode> episodeList) {
        if (episodeList != null) {
            mEpisodes = episodeList;
            if (mPlayData != null) {
                mPlayData.setEpisodes(episodeList);
                setSelectListData();
            }
        }
    }

    private boolean isEpisodeGridview(String vt) {
        boolean isGridview = false;
        if (mPlayData != null) {
            if (MoviesConstant.VT_TV.equals(vt)
                    || MoviesConstant.VT_CARTOON.equals(vt)) {
                isGridview = true;
            }
        }
        return isGridview;
    }

    private void setSelectListData() {
        if (isEpisodeGridview(mPlayData.getVt())) {
            String[] titleArr = new String[mPlayData.getVideoBean().getEpisodePageList().size()];
            for (int i = 0; i < mPlayData.getVideoBean().getEpisodePageList().size(); i++){
                titleArr[i] = mPlayData.getVideoBean().getEpisodePageList().get(i);
            }
            mFullEpisodePagerAdapter = new EpisodePagerAdapter(((FragmentActivity)mSelfOwnActivity).getSupportFragmentManager(), mSelfOwnActivity, mPlayData.getVideoBean(), mPlayData.getSite(), mPlayData.getVideoBean().getEpisodePageList(), true, "fullScreen");
            mFullViewPager.setAdapter(mFullEpisodePagerAdapter);
            mFullTabs.setViewPager(mFullViewPager, titleArr);
            mFullTabs.setCurrentTab(0);
            if(titleArr.length == 1){
                mFullTabs.setVisibility(View.GONE);
            }
        } else {
            String[] titleArr = new String[mPlayData.getVideoBean().getEpisodePageList().size()];
            for (int i = 0; i < mPlayData.getVideoBean().getEpisodePageList().size(); i++){
                titleArr[i] = mPlayData.getVideoBean().getEpisodePageList().get(i);
            }
            mFullEpisodePagerAdapter = new EpisodePagerAdapter(((FragmentActivity)mSelfOwnActivity).getSupportFragmentManager(), mSelfOwnActivity, mPlayData.getVideoBean(), mPlayData.getSite(), mPlayData.getVideoBean().getEpisodePageList(), false, "fullScreen");
            mFullViewPager.setAdapter(mFullEpisodePagerAdapter);
            mFullTabs.setViewPager(mFullViewPager, titleArr);
            mFullTabs.setCurrentTab(0);
            if(titleArr.length == 1){
                mFullTabs.setVisibility(View.GONE);
            }
        }
    }

    /**
    * 请求分页数据 zhangshuo 2015年3月6日 下午4:51:03
     */
    private void requestPageInfos(String getDataOrder) {
        mCurrOrder = getDataOrder;
        RequestVideoPageInfoTask requestPageInfosTask = new RequestVideoPageInfoTask(
                MoviesApplication.getInstance());
        requestPageInfosTask.setEpisodes(mEpisodes);
        requestPageInfosTask.setSetDataOrder(getDataOrder);
        requestPageInfosTask.setAid(mPlayData.getAid());
        requestPageInfosTask.setSite(mPlayData.getSite());
        requestPageInfosTask.setPageIndex(mCurrPage);
        requestPageInfosTask.setPageSize(PAGESIZE);
        requestPageInfosTask.setmListener(new RequestPageInfoListener());
        requestPageInfosTask.start();
    }

    @Override
    public boolean onLetvSdkError(MediaPlayer mp, String code, int extra) {
        showErrorCodeForDebug(0,code);
        if(mPlayEpisode != null && !TextUtils.isEmpty(mPlayEpisode.getExternalId())){
            mPlayStatusReport = new PlayStatusReporter();
            mPlayStatusReport.setAction(MoviesConstant.STATE_ACTION_PLAY);
            mPlayStatusReport.setPorder(mPlayEpisode.getPorder());
            mPlayStatusReport.setVid(mSnifferUrl);
            mPlayStatusReport.setExternal_id(mPlayEpisode.getExternalId());
            mPlayStatusReport.setGlobal_vid(mPlayEpisode.getGlobaVid());
            String reportSubsrc = TextUtils.isEmpty(mPlayEpisode.getSite()) ? mPlayData.getSite() : mPlayEpisode.getSite();
            mPlayStatusReport.setSubsrc(reportSubsrc + "sdk");
            mPlayStatusReport.setAid(mReportAid);
            mPlayStatusReport.setVt(mPlayData.getVt());
            String errorInfo = "";
            if (mPlayContorl != null && mPlayContorl instanceof LVideoMediaPlayerControl) {
                if(((LVideoMediaPlayerControl)mPlayContorl).getFirstErrorCode() != 0){
                    errorInfo = errorInfo + "F" + ((LVideoMediaPlayerControl)mPlayContorl).getFirstErrorCode();
                }
            }
            if(!TextUtils.isEmpty(code)){
                errorInfo = errorInfo + "S" + code;
            } else {
                errorInfo = errorInfo + "S" + "null";
            }
            if (extra != 0){
                errorInfo = errorInfo + "T" + extra;
            }
            if(!TextUtils.isEmpty(errorInfo)){
                mPlayStatusReport.setmErrorInfo(errorInfo);
            }
        }
        return onErrorPlayLogic(null, 0,extra,true);
    }

    private class RequestPageInfoListener implements
       RequestResultListener<PageInfoData> {
            @Override
        public boolean onRequestFailed() {
            if (PlayerUtils.FIRST.equals(mCurrOrder)) {
                ++mCurrPage;
             } else if (PlayerUtils.END.equals(mCurrOrder)) {
                --mCurrPage;
            }
            return false;
        }
        @Override
        public void onRequestSuccess(int updateId, PageInfoData result) {
            if (null != result && null != result.getmEpisodes()
                    && result.getmEpisodes().size() > 0) {
                // 获取最新的Episode数据列表
                mEpisodes = result.getmEpisodes();
                // 根据当前的位置查找Episode并执行相关逻辑
                Episode episode = findEpisodeByPorder(mPorderList
                        .get(mVideoPosition));
                mPlayDataReport = new PlayDataReporter();
                isFirstDragReported = false;
                if (PlayerUtils.SITE_CLOUDDISK.equals(mPlayData.getSite())) {
                    lvideoVideoCode = PlayerUtils.PLS_MP4_350;  //云盘切集之后重置清晰度
                }
                ischangeClarity = false;
                mIsAllowLetvSdk = true;
                executeCommonPlay(episode);
                setSelectListData();
            }
        }
        @Override
        public void onPreRequest() {

         }
    }



    private Episode findEpisodeByPorder(String porder) {
        if (mEpisodes == null) {
            return null;
        }
        for (int i = 0; i < mEpisodes.size(); i++) {
            Episode episode = mEpisodes.get(i);
            if (porder.equals(episode.getPorder())) {
                return episode;
            }
        }
        return null;
    }

    private int getCurrPage(int position) {
        int currPage = 0;
        if (0 == position || (position + 1) % PAGESIZE > 0) {
            currPage = (position + 1) / PAGESIZE + 1;
        } else {
            currPage = (mVideoPosition + 1) / PAGESIZE;
        }
        return currPage;
    }

    /**
     * 本地播放
     *
     * @param localVideoEpisode
     */
    private void executeLocalPlayLogic(LocalVideoEpisode localVideoEpisode) {
        mPlayDataReport = new PlayDataReporter();
        setUMengReprot();
        setTitleText(localVideoEpisode.getName());
        setReportMid(localVideoEpisode); //设置本地播放mid
        if (TextUtils.isEmpty(localVideoEpisode.getGlobaVid())) {
            bigDataPlayReporter.setVid(localVideoEpisode.getAid());
        } else {
            bigDataPlayReporter.setVid(localVideoEpisode.getGlobaVid());
        }
        bigDataPlayReporter.setRef(localVideoEpisode.getPlay_url().get(0));
        bigDataPlayReporter.setPy(localVideoEpisode.getName(),
                localVideoEpisode.getSite());
        mPlayDataReport.setAid(mPlayData.getAid() == null ? "" : mPlayData.getAid());
        mPlayDataReport.setMid(localVideoEpisode.getMid() == null ? "" : localVideoEpisode.getMid());
        mPlayDataReport.setCloudId(localVideoEpisode.getCloudId() == null ? "" : localVideoEpisode.getCloudId());
        mPlayDataReport.setGlobalVid(localVideoEpisode.getGlobaVid() == null ? "" : localVideoEpisode.getGlobaVid());
        mPlayDataReport.setPorder(localVideoEpisode.getPorder() == null ? "" : localVideoEpisode.getPorder());
        mPlayDataReport.setVid("");
        mPlayDataReport.setSource(localVideoEpisode.getSite());
        mPlayDataReport.setVt(localVideoEpisode.getVt());
        String downloadType = localVideoEpisode.getDownType();
        ArrayList<String> playUrl = new ArrayList<>();
        if (PlayerUtils.DOWNLOAD_M3U8.equalsIgnoreCase(downloadType)) {
            PlayerUtils.DEFAULT_PLAYER_TYPE = MyPlayerConstant.MOBILE_MY_M3U8;
            StringBuffer sbff = new StringBuffer();
            sbff.append(PlayerUtils.LOCAL_M3U8_DOMAIN);
            sbff.append(localVideoEpisode.getPlay_url().get(0));
            playUrl.add(sbff.toString());
        } else {
            PlayerUtils.DEFAULT_PLAYER_TYPE = MyPlayerConstant.MOBILE_MY_MP4;
            playUrl = localVideoEpisode.getPlay_url();
        }
        mStream_list = playUrl;
        mStreamIndex = 0;
        mIsFirstTime = true;
        doPlayLocalVideo(mStream_list.get(0));
    }

    /**
     * 当前播放的视频
     *
     * @param porder zhangshuo 2014年6月11日 上午10:00:06
     */
    private LocalVideoEpisode getCurrLocalEisode(String porder) {
        if (!TextUtils.isEmpty(porder) && null != mLocalPlayLists
                && mLocalPlayLists.size() > 0) {
            int playSize = mLocalPlayLists.size();
            boolean isFindEpisode = false;
            // 查找当前影片位置
            for (int i = 0; i < playSize; i++) {
                LocalVideoEpisode localVideoEpisode = mLocalPlayLists.get(i);
                if (null != localVideoEpisode) {
                    if (porder.equals(localVideoEpisode.getPorder())) {
                        mVideoPosition = i;
                        isFindEpisode = true;
                        return localVideoEpisode;
                    }
                }
            }
            // 如果没找到则取第一个
            if (!isFindEpisode) {
                mVideoPosition = 0;
                return mLocalPlayLists.get(0);
            }
        }
        return null;
    }

    private void executeCommonPlay(Episode episode) {
        // 在线播放默认使用软解播放
        if (mSelfOwnActivity != null && mSelfOwnActivity instanceof VideoDetailActivity
                && !((PlayCallBackListener) mSelfOwnActivity).onRefreshPlayerListener(mVideoPosition)) {
            if (mVideoViewPosition != null) {
                mVideoViewPosition.setVisibility(View.GONE);
            }
            if (mMediaController != null) {
                mMediaController.setVisibility(View.GONE);
            }
            setSelectLayoutVisibile(false);
            return;
        } else {
            if (mVideoViewPosition != null) {
                mVideoViewPosition.setVisibility(View.VISIBLE);
            }
            if (mMediaController != null) {
                mMediaController.setVisibility(View.VISIBLE);
            }
        }
        PlayDecodeMananger.setmNeedSysDecoder(false);
        PlayerUtils.DEFAULT_PLAYER_TYPE = PlayDecodeMananger
                .getCurrPlayerType();
        if (mPlayEpisode != null && !mPlayEpisode.getPorder().equals(episode.getPorder())) {
            mPlayEpisode.setAdPlayed(false);
        }
        mIsJSFailed = false;
        mIsJSSuccessed = false;
        mIsPlayingAdvertisement = false;
        mPlayEpisode = episode;
        // 设置友盟上报
        setUMengReprot();
        bigDataPlayReporter.genUUID();
        bigDataPlayReporter.setVid(episode.getVid());
        bigDataPlayReporter.setSource(TextUtils.isEmpty(mPlayEpisode.getSite()) ? mPlayData.getSite() : mPlayEpisode.getSite());
        if ("letv".equalsIgnoreCase(mPlayData.getSite())) {
            bigDataPlayReporter.setMid(mPlayEpisode.getMid());
            bigDataPlayReporter.setOwner(BigDataConstants.OWNER_IN); // 乐视源
        } else if (PlayerUtils.SITE_CLOUDDISK.equals(mPlayData.getSite())) {
            bigDataPlayReporter.setOwner(BigDataConstants.OWNER_OUT); // 网盘播放
            bigDataPlayReporter.setMid(mPlayEpisode.getCloudId());
        } else {
            bigDataPlayReporter.setOwner(BigDataConstants.OWNER_OUT); // 外网播放
            bigDataPlayReporter.setMid(mPlayEpisode.getGlobaVid());
        }

        // 设置标题栏名称
        setVideoName(episode);
        bigDataPlayReporter.onPlayerInit(); // 播放器初始化上报
        isBigDataInit = true;

        mUMengReport.setVid(episode.getVid());
        mPlayDataReport.setAid(mPlayData.getAid() == null ? "" : mPlayData.getAid());
        mPlayDataReport.setMid(episode.getMid() == null ? "" : episode.getMid());
        mPlayDataReport.setCloudId(episode.getCloudId() == null ? "" : episode.getCloudId());
        mPlayDataReport.setGlobalVid(episode.getGlobaVid() == null ? "" : episode.getGlobaVid());
        mPlayDataReport.setPorder(episode.getPorder() == null ? "" : episode.getPorder());
        mPlayDataReport.setVid(episode.getVid() == null ? "" : episode.getVid());
        mPlayDataReport.setSource(mPlayData.getSite());
        mPlayDataReport.setVt(mPlayData.getVt());

        /**
         * 在此处判断当前是否需要请求分页接口，当前mid和gloadvid均为空时则认为需要请求分页接口
         */
        String site = mPlayData.getSite();
        // 如果存在则执行正常的播放逻辑就OK了
        executeProcessBySite(site);
        selfReportPlayInit();
    }

    @Override
    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
        onFullScreen();
    }

    public void unitPptv() {
        if (mPptvInit) {
            PPTVSdkMgr.getInstance().unit(MoviesApplication.getInstance());
            PPTVSdkMgr.getInstance().unInitVideoView();
            PPTVSdkMgr.getInstance().setOnPlayerStatusListener(null);
            mPptvInit = false;
        }
    }

    private void init() {
        String tunnel = "2499"; //ChannelUtil.getChannel(mSelfOwnActivity);

        String param = String.format("%s=%s",
                PPTVSdkParam.Config_Tunnel, tunnel);
//        if (mPptvInit) {
//            PPTVSdkMgr.getInstance().unit(getmActivity());
//        } else {
        String libPath = null; // for example: /storage/sdcard1/Android/data/com.pplive.videoplayer.test/cache
        try {
            PPTVSdkMgr.getInstance().init(MoviesApplication.getInstance(), null, param, libPath);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return;
        }
        mPptvInit = true;
//        }

    }

    private VideoViewFunshionProxy funshionProxy;

    /**
     * 区分站点，执行播放
     *
     * @param site
     */
    private void executeProcessBySite(String site) {   // 贴片广告请求，放在这里,下面代码放在请求结果中
        if (mIsFullScreen) {
            statusBarShow(false);// 隐藏状态栏
        }
        LogCat.e("wym", "!!!!!!!!!!!!!!!!!!!cur play source is " + isLVideoSource());
        if (null != mOutSiteStreamInfoTask && !mOutSiteStreamInfoTask.isCancelled()) {
            mOutSiteStreamInfoTask.cancel();
        }
        mLinkShellUrl = null;
        isInPlayingProcess = false;
        mIsFirstTime = true;
        mTimeMillis = System.currentTimeMillis();
        if (mVideoViewPosition != null) {
            // 去掉贴片广告view
            if (null != mPlayPasterAdView) {
                mPlayPasterAdView.setVisibility(View.GONE);
                mVideoViewPosition.removeView(mPlayPasterAdView);
            }
            // 去掉风行广告view
            if (null != funshionProxy) {
                funshionProxy.removeAdPlayerView(mVideoViewPosition);
            }
        }
        attachAdLinearLayout.setVisibility(View.GONE);
        attachAdBottomLinearLayout.setVisibility(View.GONE);
        setSound(false);
        if (!TextUtils.isEmpty(site)) {
            if (Constants.SDK_TENCENT.equals(mPlayData.getPlayer())
                    && !TextUtils.isEmpty(mPlayEpisode.getExternalId())) {
                if (null != mVideoViewPosition && null != mPlayerView) {
                    mPlayerView.setVisibility(View.GONE);
                    mVideoViewPosition.removeView(mPlayerView);
                    LogCat.e(Utils.TAG, "remove mPlayerView ");
                }
                // 腾讯视频
                mIsSdkPlayer = true;
                mPlayContorl = mVideoViewBuilder.build(mSelfOwnActivity, MyPlayerConstant.MOBILE_TENCENT_SDK);
                LogCat.e(Utils.TAG, "init mPlayContorl tencent");
                // 加载view到布局
                mPlayerView = mPlayContorl.getView();
                //fix home page animation play on surface view bug, in huawei device
                mPlayerView.setVisibility(View.INVISIBLE);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mPlayerView.setVisibility(View.VISIBLE);
                    }
                }, 300);
                RelativeLayout.LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
                params.addRule(RelativeLayout.CENTER_IN_PARENT);
                mVideoViewPosition.addView(mPlayerView, params);
                mVideoViewPosition.setBackgroundColor(Color.BLACK);

                setPlayerListener();
                mPlayContorl.setOnVideoSizeChangedListener(this);
                TVK_UserInfo mUserinfo = new TVK_UserInfo("", "");
                TVK_PlayerVideoInfo mPlayerinfo = new TVK_PlayerVideoInfo(TVK_PlayerMsg.PLAYER_TYPE_ONLINE_VOD, mPlayEpisode.getExternalId(), "");

                mPlayerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        if (UIs.isOnScreenTop(mPlayerView) && UIs.isScreenOriatationPortrait(mSelfOwnActivity)) {
                            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mPlayerView.getLayoutParams();
                            params.topMargin = UIs.getStatusBarHeight();
                            mPlayerView.setLayoutParams(params);
                        } else if (!UIs.isScreenOriatationPortrait(mSelfOwnActivity)) {
                            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mPlayerView.getLayoutParams();
                            params.topMargin = 0;
                            mPlayerView.setLayoutParams(params);
                        }
                    }
                });

                if (mPlayContorl instanceof LVideoMediaPlayerControl) {
                    ((LVideoMediaPlayerControl) mPlayContorl).setTencentData(mUserinfo, mPlayerinfo, (int) (mPlayData.getmPlayRecord()
                            .getSeekHistory()));
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (mPlayContorl != null && mPlayContorl instanceof LVideoMediaPlayerControl) {
                                mSohuDefinitionList = ((LVideoMediaPlayerControl) mPlayContorl).getSupportDefinitions();
                                mClaritymap = DefinitionManager
                                        .getSupportDefMapOnlyOuter(
                                                (ArrayList<Integer>) mSohuDefinitionList);
                                setSohuPlayerDefinition(((LVideoMediaPlayerControl) mPlayContorl).getCurrentDefinition());
                                // 设置影片总长
                                mTotalTime.setText(PlayerUtils.toStringTime((int) mDuration));
                            }
                        }
                    }, 5000);
                }
            } else if (Constants.SDK_PPTV.equals(mPlayData.getPlayer())
                    && !TextUtils.isEmpty(mPlayEpisode.getExternalId())) {
                if (mPlayEpisode != null && mPlayEpisode.getAdPlayed()) {
                    doPptvSdkPlay();
                } else {
                    requestPasterAd();  //先请求广告
                }
            } else if (Constants.SDK_LETV.equals(mPlayData.getPlayer())
                    && !TextUtils.isEmpty(mPlayEpisode.getExternalId()) && mIsAllowLetvSdk) {
                // 乐视SDK
                mHandler.removeMessages(Utils.AD_SECOND);
                attachAdLinearLayout.setVisibility(View.GONE);
                attachAdBottomLinearLayout.setVisibility(View.GONE);
                MoviesConstant.letvPlayStatus = 1;
                if (mPlayEpisode != null && mPlayEpisode.getAdPlayed()) {
                    doLetvSdkPlay();
                } else {
                    requestPasterAd();  //先请求广告
                }
            } else if (Constants.SDK_BESTV.equals(mPlayData.getPlayer()) && !TextUtils.isEmpty(mPlayEpisode.getExternalId())) {
                if (null != mVideoViewPosition && null != mPlayerView) {
                    mPlayerView.setVisibility(View.GONE);
                    mVideoViewPosition.removeView(mPlayerView);
                    LogCat.e(Utils.TAG, "remove mPlayerView ");
                }
                if (!VideoViewShell.IsInitializedComplete()) {
                    // 初始化
                    try {
                        // 初始化百事通sdk
                        VideoViewShell.InitShellApplicationContext(mSelfOwnActivity.getApplicationContext(), new InitShellApplicationContextListener() {
                            @Override
                            public void onInitComplete() {
                                BestvSdkPlay();
                            }

                            @Override
                            public void onInitFailed() {
                                BestvSdkPlay();
                            }
                        });
                    } catch (Exception e) {
                    }
                } else {
                    BestvSdkPlay();
                }
            } else if (Constants.SDK_FUNSHION.equals(mPlayData.getPlayer()) && !TextUtils.isEmpty(mPlayEpisode.getExternalId())) {
                if (null != mVideoViewPosition && null != mPlayerView) {
                    mPlayerView.setVisibility(View.GONE);
                    mVideoViewPosition.removeView(mPlayerView);
                    LogCat.e(Utils.TAG, "remove mPlayerView ");
                }
                System.out.println("--->" + mIsPause);
                funshionProxy = (VideoViewFunshionProxy) mVideoViewBuilder.build(mSelfOwnActivity, MyPlayerConstant.MOBILE_FUNSHION_SDK);
                funshionProxy.setupView(mVideoViewPosition);
                funshionProxy.setCallback(new VideoViewFunshionProxy.Callback() {
                    @Override
                    public void startPlay(String url) {
                        doPlay(MyPlayerConstant.MOBILE_FUNSHION_SDK, url);
                    }

                    @Override
                    public void onAdStart() {
                        onAdStarted();
                    }

                    @Override
                    public void onAdEnd() {
                        onAdFinished();
                    }

                    @Override
                    public void onFailed(FSError error) {
                        onError(null, error.getErrorCode(), 0);
                    }

                    @Override
                    public void onDefinition(final List<Integer> definitions, final int curDefinition) {
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                mClaritymap = DefinitionManager
                                        .getSupportDefMapOnlyOuter(
                                                (ArrayList<Integer>) definitions);
                                setSohuPlayerDefinition(curDefinition);
                            }
                        });
                    }
                });
                mIsSdkPlayer = true;
                mPlayContorl = funshionProxy;
                RequestFsTokenTask tokenTask = new RequestFsTokenTask(MoviesApplication.getInstance());
                tokenTask.start();
            } else {
                if (!TextUtils.isEmpty(mPlayEpisode.getMid()) && ("0".equals(SharePreferenceManager.getVaule(mSelfOwnActivity, SharePreferenceManager.PRIMEPLAYTYPE, "1"))) ) {// 判断是否是乐视源，有mid的为乐视源
                    excuteLetvProcess();
                } else {
                    executeOutSiteProcess();
                }
            }
        }
    }

    private void BestvSdkPlay() {
        mIsSdkPlayer = true;
        mPlayContorl = mVideoViewBuilder.build(mSelfOwnActivity, MyPlayerConstant.MOBILE_BESTV_SDK);
        mPlayerView = mPlayContorl.getView();
        RelativeLayout.LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        params.addRule(RelativeLayout.CENTER_IN_PARENT);
        mVideoViewPosition.addView(mPlayerView, params);
        mVideoViewPosition.setBackgroundColor(Color.BLACK);
        setPlayerListener();
        String[] listStr = mPlayEpisode.getExternalId().split(",");
        String vid = listStr.length > 0 ? listStr[0] : "";
        String fdnCode = listStr.length > 1 ? listStr[1] : "";
        if (mPlayContorl instanceof LVideoMediaPlayerControl) {
            ((LVideoMediaPlayerControl) mPlayContorl).setBestvData(vid, fdnCode, mPlayData.getmPlayRecord()
                    .getSeekHistory());
        }
    }

    private void excuteLetvProcess() {
        bigDataPlayReporter.setMid(mPlayEpisode.getMid());
        bigDataPlayReporter.setOwner(BigDataConstants.OWNER_IN); // 乐视源
        bigDataPlayReporter.setSource("letv");
        CdeHelper cdeHelper = mCDEManager.getmCdeHelper();
        // 判断当前CDE服务是否启动
        if (cdeHelper.isReady()) {
            LogCat.e(TAG, "!!!!!!!CDE服务是启动的");
            executeInSiteProcess();
        } else {
            LogCat.e(TAG, "!!!!!!!CDE服务是启动的1");
            mCdeStatusReiver = new CDEStatusReceiver();
            mSelfOwnActivity.registerReceiver(mCdeStatusReiver,
                    new IntentFilter(CdeService.ACTION_CDE_READY));
            try {
                mCDEManager.startCde();
            } catch (Exception e) {
                LogUtils.e("Start cde error:" + e.getMessage());
            }
        }
    }

    /**
     * 设置搜狐sdk播放时的清晰度显示
     */
    private void setSohuPlayerDefinition(int crrentClarity) {
        mClarityPopupWindow.initCloudClarityUI(mClaritymap, String.valueOf(crrentClarity));

        DefinitionManager.DefinitionObj definitionObj
                = DefinitionManager.checkDefClassify(String.valueOf(crrentClarity));
        if (definitionObj != null) {
            mClarity_select.setText(definitionObj.showTextResId);
        }
    }

    private void setUMengReprot() {
        if (null != mUMengReport) {
            // 设置当前开始加载的时间
            mUMengReport.setStartLoadingTime(System.currentTimeMillis());
            mUMengReport.setAid(mPlayData.getAid());
            mUMengReport.setName(mPlayData.getmViewName());
            mUMengReport.setCategoryName(mPlayData.getCategoryName());
            // 判断
            String from = (mPlayData.getFrom());
            mUMengReport.setFrom(from);
        }
    }

    /**
     * 设置标题栏影片名称
     *
     * @param episode zhangshuo 2014年5月7日 下午1:30:09
     */
    private void setVideoName(Episode episode) {
        if (null != mPlayData.getmPlayRecord()) {
            if (mPlayData.getmPlayRecord().getSeekHistory() > 0) {
                mVideoName = PlayerUtils.getVideoName(mPlayData, mPlayData.getVt(), mPlayData.getmPlayRecord().getName(), episode);
            } else {
                if (!TextUtils.isEmpty(mPlayData.getFrom()) && mPlayData.getFrom().equals("history")) {
                    mVideoName = mPlayData.getmPlayRecord().getName();
                    if (TextUtils.isEmpty(mVideoName) || !mVideoName.equals(mPlayData.getmViewName()) || !mPlayData.getPorder().equals(episode.getPorder())) {
                        mVideoName = PlayerUtils.getVideoName(mPlayData, mPlayData.getVt(), mPlayData.getmViewName(), episode);
                    }
                } else if (TextUtils.isEmpty(mVideoName) || !mPlayData.getFrom().equals("history")) {
                    mVideoName = PlayerUtils.getVideoName(mPlayData, mPlayData.getVt(), mPlayData.getmViewName(), episode);
                }
                mPlayData.getmPlayRecord().setName(mPlayData.getmViewName());
            }
        }
        setTitleText(mVideoName);
        bigDataPlayReporter.setRef(episode.getPlay_url());
        bigDataPlayReporter.setPy(mVideoName, mPlayData.getSite());
        if (Constants.SDK_TENCENT.equals(mPlayData.getPlayer()) || Constants.SDK_PPTV.equals(mPlayData.getPlayer())
                || Constants.SDK_LETV.equals(mPlayData.getPlayer())
                || Constants.SDK_BESTV.equals(mPlayData.getPlayer())
                || Constants.SDK_FUNSHION.equals(mPlayData.getPlayer())) {
            bigDataPlayReporter.setPy(bigDataPlayReporter.getPy() + "&player=sdk");
        }
    }

    /**
     * 执行站内播放流程 zhangshuo 2014年5月6日 下午1:29:03
     */
    private void executeInSiteProcess() {
        mIsSdkPlayer = false;
        bigDataPlayReporter.setOwner(BigDataConstants.OWNER_IN); // 内网播放
        bigDataPlayReporter.setSource(TextUtils.isEmpty(mPlayEpisode.getSite()) ? mPlayData.getSite() : mPlayEpisode.getSite());
        if (null != mPlayEpisode && !TextUtils.isEmpty(mPlayEpisode.getPls())) {
            String[] types = mPlayEpisode.getPls().split(",");
            videoCaseList = new ArrayList<>();
            for (String type:types) {
                if (!TextUtils.isEmpty(type)){
                    videoCaseList.add(type);
                }
            }
            if (UIs.isScreenOriatationPortrait(mSelfOwnActivity)) {
                mClarity_select.setVisibility(View.GONE);
            } else {
                mClarity_select.setVisibility(View.VISIBLE);
            }
            defaultClarity(videoCaseList);
            checkClarity(videoCaseList);
            bigDataPlayReporter.setMid(mPlayEpisode.getMid());
            // 判断当前是否有兼容的MP4码流
            if (videoCaseList.contains(lvideoVideoCode)) {
                if (DefinitionManager.checkDefTypeInLetv(lvideoVideoCode)) {
                    mdefaultClarity = DefinitionManager.getLetvVtype(lvideoVideoCode);
                }
                // 当不是流畅模式时，超过10秒缓冲就显示切换清晰度提示
                if (!lvideoVideoCode.equals(PlayerUtils.PLS_MP4)) {
                    mHandler.sendEmptyMessageDelayed(
                            Utils.VIDEO_SHOW_CHANGE_CLARITY,
                            Utils.MEDIA_CONTROLLER_SHOW_TIME);
                }
                mSnifferUrl = mPlayEpisode.getPlay_url();
                LogCat.e(TAG, "lvideo site mSnifferUrl is " + mSnifferUrl);
                if (!mRequestVStreamListTask.isCancelled()) {
                    mRequestVStreamListTask.cancel();
                }

                mPlayStatusReport = new PlayStatusReporter();
                mPlayStatusReport.setAction(MoviesConstant.STATE_ACTION_PLAY);
                mPlayStatusReport.setPorder(mPlayEpisode.getPorder());
                mPlayStatusReport.setVid(mPlayEpisode.getMid());
                mPlayStatusReport.setExternal_id(mPlayEpisode.getExternalId());
                mPlayStatusReport.setGlobal_vid(mPlayEpisode.getGlobaVid());
                String src = TextUtils.isEmpty(mPlayEpisode.getSite()) ? mPlayData.getSite() : mPlayEpisode.getSite();
                mPlayStatusReport.setSubsrc(src + "305");
                mPlayStatusReport.setSrartRequestTime(System.currentTimeMillis());
                mPlayStatusReport.setAid(mReportAid);
                if (mPlayData != null) {
                    mPlayStatusReport.setVt(mPlayData.getVt());
                }


                Bundle b = new Bundle();
                // 3053093
                b.putString(MoviesHttpApi.LeTvBitStreamParam.KEY_MMSID,
                        mPlayEpisode.getMid());
                bigDataPlayReporter.setMid(mPlayEpisode.getMid());
                b.putString(MoviesHttpApi.LeTvBitStreamParam.KEY_PLS,
                        lvideoVideoCode);
                // b.putString(MoviesHttpApi.LeTvBitStreamParam.KEY_REQUESTTYPE,
                // PlayerUtils.PLAY);
                // MoviesHttpApi.LeTvBitStreamParam.KEY_CDETYPE_TEST
                b.putString(MoviesHttpApi.LeTvBitStreamParam.KEY_CDETYPE,
                        MoviesHttpApi.LeTvBitStreamParam.KEY_CDETYPE_AES);
                b.putString(MoviesHttpApi.LeTvBitStreamParam.KEY_REQUESTTYPE,
                        LeTvBitStreamParam.KEY_PLAY);
                b.putString(MoviesHttpApi.LeTvBitStreamParam.KEY_VID,
                        mPlayEpisode.getVid());
                //TODO
//                bigDataPlayReporter.setStreamType(PlayerUtils.VT_MP4_350);
                mRequestVStreamListTask.setParams(b);
                mRequestVStreamListTask.start();
                LogCat.e(TAG, "!!!!!!!!!!!!!!!!!!!mRequestVStreamListTask start!!!!!!!!!!!!!!!!!!!");
                UmengEventPoster.doEventPost(UmengPostConstant.PlayVideo_lvideo); //播乐视源友盟上报
                MoviesConstant.letvPlayStatus = 0;
            } else {
                bigDataPlayReporter.onPlayError(true, BigDataConstants.PLAY_PLS_ERR);
                // 如果当前不存在Mp4兼容的码流则报错跳转至网页播放
                jumpToWebPlayeActivity();
            }
        } else {
            bigDataPlayReporter.onPlayError(true, BigDataConstants.VIDEO_NOT_FOUND_ERR);
            jumpToWebPlayeActivity();
        }
    }

    /**
     * 判断默认清晰度
     */
    private void defaultClarity(List<String> typeList) {
        // 当前需要获取的视频编码格式,先查找标清片源是否存在查找兼容片源是否存在
        if (!typeList.contains(lvideoVideoCode)) {
            lvideoVideoCode = PlayerUtils.PLS_MP4;
        }
        DefinitionManager.DefinitionObj definitionObj = DefinitionManager.checkDefClassify(lvideoVideoCode);
        if (definitionObj != null) {
            mClarity_select.setText(definitionObj.showTextResId);
            bottomTips = mSelfOwnActivity.getResources().getString(definitionObj.showTextResId);
        }
    }

    /**
     * 检测三种清晰度数据是否可用
     */
    private void checkClarity(ArrayList<String> typeList) {
        mClaritymap = DefinitionManager.getSupportDefFlag(typeList);
    }

    /**
     * 乐视源 网盘源 数据请求失败后10s再次请求
     * 清晰度 252009流畅 252021标清 252022高清
     */
    private void reTryPlay() {
        mHandler.postDelayed(new Runnable() {

            @Override
            public void run() {
                if (mInSiteRetryTime < 3) {
                    mInSiteRetryTime++;
                    LogUtils.e(TAG, "!!!!!!!!!!!!!!again request data!!!!!!!!!!!!!!");
                    executeClarityChangePlay();
                }
            }

        }, Utils.MEDIA_CONTROLLER_SHOW_TIME);
    }

    /**
     * 请求主站码流失败
     */
    @Override
    public boolean onRequestFailed() {
        LogCat.e(TAG, "!!!!!!!!!!!!!!!!!!!!!request lvideo play data failed and reason maybe is user click too much in one minute!!!!!!!!!!!!!!!!!!!!!");
//        reTryPlay();
        mPlayStatusReport.setEndRequestTime(System.currentTimeMillis());
        reportPlayState(MoviesConstant.GET_PLAYURL_FAIL_STATE, "", "");
        return false;
    }

    @Override
    public boolean onRequestFailed(String code, String msg) {
        mPlayStatusReport.setEndRequestTime(System.currentTimeMillis());
        if (MoviesConstant.RESPONSE_NO_NET_ERROR.equals(code)) {
            reportPlayState(MoviesConstant.SERVER_PLAY_NETS_ERROR, "", "");
        } else if ("503".equals(code)) {
            reportPlayState(MoviesConstant.GET_PLAYURL_FAIL_503, "", "");
        } else if ("211".equals(code)) {
            reportPlayState(MoviesConstant.GET_PLAYURL_FAIL_211, "", "");
        } else if ("212".equals(code)) {
            reportPlayState(MoviesConstant.GET_PLAYURL_FAIL_212, "", "");
        } else if (MoviesConstant.RESPONSE_DATA_ERROR.equals(code)) {
            reportPlayState(MoviesConstant.GET_PLAYURL_FAIL_STATE, "", msg);
        } else {
            reportPlayState(MoviesConstant.GET_PLAYURL_FAIL_STATE, code, "");
        }
        return false;
    }

    /**
     * 请求站内码流成功（lvideo源不包括网盘）
     */
    @Override
    public void onRequestSuccess(int updateId, VStreamInfoList result) {
        mPlayStatusReport.setEndRequestTime(System.currentTimeMillis());
        if (null != result.get(mdefaultClarity)) {
            String url = result.get(mdefaultClarity).getMainUrl();
            String resultUrl = "";
            if (!TextUtils.isEmpty(url)) {
                mInSiteRetryTime = 3; //请求成功直接设置为3，无需重试
                LogCat.e(TAG, "!!!!!!!!!!!!!!!!!!!!!request lvideo play data sucess and lvideoPlayUrl is " + url);
                LogCat.e("wym", "lvideo cde called and cur uuid " + bigDataPlayReporter.getUUID());
                bigDataPlayReporter.genUUID(); // 在拿到cde调度地址时，构造当前播放器uuid
                LogCat.e("wym", "!!!!!!!!!!!!!!!!!!!!!before addPlatCode lvideoPlayUrl is " + url);
                String uuid = bigDataPlayReporter.getUUID();
                String vid = mPlayEpisode.getMid();// vid取mid
                LogCat.e("wym", "!!!!!!!!!!!!!!uuid is " + uuid + " and mid is " + vid);
                LogCat.e("wym", "vid is " + mPlayEpisode.getVid() + " and cloudid is " + mPlayEpisode.getCloudId() + " and gvid is " + mPlayEpisode.getGlobaVid());
                // add platParam && (add uuid,vid || uuid,liveid)
                url = PlayerUtils.addPlatCode(url, uuid, vid);
                CdeHelper cdeHelper = mCDEManager.getmCdeHelper();
                mLinkShellUrl = cdeHelper.getLinkshellUrl(url);
                LogCat.e("wym", "$$$$$$$$mLinkShellUrl$$$$$$" + mLinkShellUrl);
                resultUrl = cdeHelper.getPlayUrl(mLinkShellUrl);
                int currPlayType = PlayDecodeMananger.getCurrPlayerType();
                if (!TextUtils.isEmpty(resultUrl)) {
                    LogCat.e("wym", "乐视cdeurl-----------" + resultUrl);
                    doPlay(currPlayType, resultUrl);
                }
            } else {
                reportPlayState(MoviesConstant.GET_PLAYURL_FAIL_STATE, "", "");
            }
        } else {
            reportPlayState(MoviesConstant.GET_PLAYURL_FAIL_STATE, "", "");
        }
    }

    /**
     * 开始主站码流请求
     */
    @Override
    public void onPreRequest() {

    }

    /**
     * 执行站外播放流程 zhangshuo 2014年5月6日 下午1:29:08
     */
    private void executeOutSiteProcess() {
        playLogic(mPlayEpisode);
    }

    /**
     * 获取当前播放位置
     *
     * @param porder
     * @return zhangshuo 2015年3月10日 下午2:07:33
     */
    private int getCurrEpisodePosition(String porder) {
        int position = 0;
        if (!TextUtils.isEmpty(porder) && null != mPorderList
                && mPorderList.size() > 0) {
            int playSize = mPorderList.size();
            boolean isFindEpisode = false;
            // 查找当前影片位置
            for (int i = 0; i < playSize; i++) {
                if (porder.equals(mPorderList.get(i))) {
                    position = i;
                    isFindEpisode = true;
                }
            }
            // 如果没找到则取第一个
            if (!isFindEpisode) {
                position = 0;
            }
        }
        return position;
    }

    /**
     * 执行播放逻辑(外网)(网盘包括)
     *
     * @param episode zhangshuo 2014年5月2日 下午10:27:45
     */
    private void playLogic(Episode episode) {
        mPlayEpisode = episode;
        mSnifferUrl = episode.getPlay_url();
        LogCat.e(TAG, "cloud site order is " + episode.getSubName());
        LogCat.e(Utils.TAG, "out site mSnifferUrl is " + mSnifferUrl);
        LogCat.e(Utils.TAG, "out source play order is " + episode.getPorder());
        mSingleInfoVid = episode.getGlobaVid();
        bigDataPlayReporter.setSource(TextUtils.isEmpty(mPlayEpisode.getSite()) ? mPlayData.getSite() : mPlayEpisode.getSite());
        // 如果包含视频信息的对象或者请求单集信息的ID为空则直接跳抓网页
        if (null != mPlayEpisode && !TextUtils.isEmpty(mSingleInfoVid)) {
            // 如果是云盘资源则执行云盘自己的请求
            if (PlayerUtils.SITE_CLOUDDISK.equals(mPlayData.getSite())) {
                isCloud = true;
                bigDataPlayReporter.setOwner(BigDataConstants.OWNER_OUT); // 网盘播放
                bigDataPlayReporter.setMid(mPlayEpisode.getCloudId());
                if (PlayDecodeMananger.ismNeedSysDecoder()) {
                    PlayDecodeMananger.setmNeedSysDecoder(false);
                }
                String cloudType = PlayDecodeMananger.getCloudSourceType();
                LogUtils.d("dyf", "cloudType=" + cloudType);
                requestCloudPlay(cloudType);
            } else {
                isCloud = false;
                bigDataPlayReporter.setOwner(BigDataConstants.OWNER_OUT); // 外网播放
                bigDataPlayReporter.setMid(mPlayEpisode.getGlobaVid());
                requestOutSiteStreamInfo(null); // 新外网逻辑
            }
        } else {
            if (PlayerUtils.SITE_CLOUDDISK.equals(mPlayData.getSite()))
                bigDataPlayReporter.onPlayError(true, BigDataConstants.VIDEO_NOT_FOUND_ERR);
            else
                bigDataPlayReporter.onPlayError(false, BigDataConstants.VIDEO_NOT_FOUND_ERR);
            jumpToWebPlayeActivity();
        }
    }

    /**
     * 执行播放逻辑 (全部播放)
     *
     * @param playUrl zhangshuo 2014年9月25日 下午10:14:40
     */
    private void doPlay(final int currPlayerType, final String playUrl) {
        LogCat.e(Utils.TAG, "!!!!!!!!!!!on doPlay Method and currPlayerType is " + currPlayerType);
        if (mSelfOwnActivity != null) {
            mSelfOwnActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    LogCat.e(Utils.TAG, "into run ");
                    PlayerUtils.DEFAULT_PLAYER_TYPE = currPlayerType;
                    mCurrentPlayingUrl = playUrl;
                    if (currPlayerType == MyPlayerConstant.MOBILE_FUNSHION_SDK) {
                        //风行sdk播放特殊，
                        doTruePlay();
                    } else if (ischangeClarity || mStreamIndex > 0 || (mPlayEpisode != null && mPlayEpisode.getAdPlayed())) {//手动切清晰度和多段流播放的情况
                        doTruePlay();
                    } else {
                        mHandler.removeMessages(Utils.AD_SECOND);
                        attachAdLinearLayout.setVisibility(View.GONE);
                        attachAdBottomLinearLayout.setVisibility(View.GONE);
                        setSound(false);
                        requestPasterAd();
                    }
                }
            });
        }
    }

    //自有播放器的真正播放
    private void doTruePlay() {
        if (null != mVideoViewPosition && null != mPlayerView) {
            mPlayerView.setVisibility(View.GONE);
            mVideoViewPosition.removeView(mPlayerView);
            LogCat.e(Utils.TAG, "remove mPlayerView ");
        }
        if (null != mPlayPasterAdView) {
            mPlayPasterAdView.setVisibility(View.GONE);
            mVideoViewPosition.removeView(mPlayPasterAdView);
        }
        // 根据当前的播放器类型创建播放器View
        if (mSelfOwnActivity == null) {
            return;
        }
        if (PlayerUtils.DEFAULT_PLAYER_TYPE != MyPlayerConstant.MOBILE_FUNSHION_SDK) {
            mPlayContorl = mVideoViewBuilder.build(mSelfOwnActivity,
                    PlayerUtils.DEFAULT_PLAYER_TYPE);
            LogCat.e(Utils.TAG, "init mPlayContorl");
        }
        try {
            mPlayerView = mPlayContorl.getView();
            // 将播放器对象添加至容器中
            RelativeLayout.LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            params.addRule(RelativeLayout.CENTER_IN_PARENT);
            mVideoViewPosition.addView(mPlayerView, params);
            LogCat.e(Utils.TAG, "add mPlayerView");
            setPlayerListener();
            LogCat.e(Utils.TAG, "playUrl is " + mCurrentPlayingUrl);
            setVideoUri(mCurrentPlayingUrl);
        } catch (Exception e) {
            LogUtils.e(e.getMessage());
        }
    }

    private void doPptvSdkPlay() {
        if (null != mVideoViewPosition && null != mPlayerView) {
            mPlayerView.setVisibility(View.GONE);
            mVideoViewPosition.removeView(mPlayerView);
            LogCat.e(Utils.TAG, "remove mPlayerView ");
        }
        if (null != mPlayPasterAdView) {
            mPlayPasterAdView.setVisibility(View.GONE);
            mVideoViewPosition.removeView(mPlayPasterAdView);
        }
        PPTVSdkMgr.getInstance().unInitVideoView();
        PPTVSdkMgr.getInstance().unit(MoviesApplication.getInstance());
        init();
        mIsSdkPlayer = true;
        if (mSelfOwnActivity == null) {
            return;
        }
        mPlayContorl = mVideoViewBuilder.build(mSelfOwnActivity, MyPlayerConstant.MOBILE_PPTV_SDK);
        if (mPlayContorl instanceof VideoViewPPTVProxy && mSelfOwnActivity != null) {
            View mPptvAdView = mSelfOwnActivity.findViewById(R.id.player_ad_view);
            ImageView mPptvImageView = (ImageView) mSelfOwnActivity.findViewById(R.id.player_ad);
            TextView mPptvTextView = (TextView) mSelfOwnActivity.findViewById(R.id.player_ad_count_and_skip);
            mPptvAdView.setOnClickListener(this);
            mPptvTextView.setOnClickListener(this);
            ((VideoViewPPTVProxy) mPlayContorl).setPptvScreenView(mPptvAdView, mPptvImageView, mPptvTextView,
                    mSelfOwnActivity);
            ((VideoViewPPTVProxy) mPlayContorl).initPptv();
            mPlayerView = mPlayContorl.getView();
            RelativeLayout.LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            params.addRule(RelativeLayout.CENTER_IN_PARENT);
            mVideoViewPosition.addView(mPlayerView, params);
        }
        setPlayerListener();
        mIsPrepared = false;
        ((VideoViewPPTVProxy) mPlayContorl).setPptvDataSource(mPlayEpisode.getExternalId(), 0);
        mPlayContorl.start();
    }

    //乐视sdk播放
    private void doLetvSdkPlay(){
        if (null != mVideoViewPosition && null != mPlayerView) {
            mPlayerView.setVisibility(View.GONE);
            mVideoViewPosition.removeView(mPlayerView);
            LogCat.e(Utils.TAG, "remove mPlayerView ");
        }
        if (null != mPlayPasterAdView) {
            mPlayPasterAdView.setVisibility(View.GONE);
            mVideoViewPosition.removeView(mPlayPasterAdView);
        }
        mIsSdkPlayer = true;
        if (mSelfOwnActivity == null) {
            return;
        }
        mPlayContorl = mVideoViewBuilder.build(mSelfOwnActivity, MyPlayerConstant.MOBILE_LETV_SDK);
        MoviesConstant.letvPlayStatus = 1;
        mLetvView = (LetvPlayerView) mSelfOwnActivity.findViewById(R.id.play_view_letv);
        mLetvView.setVisibility(View.VISIBLE);
        ((LVideoMediaPlayerControl) mPlayContorl).setLetvScreenView(mLetvView);
        ((VideoViewLetvProxy) mPlayContorl).setOnLetvErrorListener(this);
        setPlayerListener();
        long lVid = Long.parseLong(mPlayEpisode.getExternalId());
        if (mPlayContorl instanceof LVideoMediaPlayerControl) {
            ((LVideoMediaPlayerControl) mPlayContorl).setLetvData(lVid,(int) (mPlayData.getmPlayRecord()
                    .getSeekHistory()));
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (mPlayContorl != null && mPlayContorl instanceof LVideoMediaPlayerControl) {
                        mSohuDefinitionList = ((LVideoMediaPlayerControl) mPlayContorl).getSupportDefinitions();
                        mClaritymap = DefinitionManager
                                .getSupportDefMapOnlyOuter(
                                        (ArrayList<Integer>) mSohuDefinitionList);
                        setSohuPlayerDefinition(((LVideoMediaPlayerControl) mPlayContorl).getCurrentDefinition());
                        // 设置影片总长
                        mTotalTime.setText(PlayerUtils.toStringTime((int) mDuration));
                    }
                }
            }, 5000);
        }
    }

    public class TestJavaScriptInterface {
        @JavascriptInterface
        public void startFunction(final String result) {
            mSelfOwnActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    LogCat.e(Utils.TAG, "xxxxxxxxxxstartFunctionxxxxxxxxxxx " + result);
                    if (!TextUtils.isEmpty(result)) {
                        parseSniffResult2(result);
                    } else {
                        handlerOutSiteError2();
                    }
                }
            });
        }

    }

    /**
     * 添加当前上报的状态
     *
     * @param state zhangshuo 2014年10月11日 下午5:09:25
     */
    private void addReportState(String state) {
        if (null == mStateList) {
            mStateList = new ArrayList<String>();
        }
        if (!mStateList.contains(state)) {
            mStateList.add(state);
        }
    }

    /**
     * 请求云盘错误接口
     *
     * @param url
     */
    private void requestCloudError(String url) {
        // 执行网盘相关请求
        if (null != mRequstCloudErrorTask && !mRequstCloudErrorTask.isCancelled()) {
            mRequstCloudErrorTask.cancel();
        }
        mRequstCloudErrorTask = new RequestCloudErrorTask(MoviesApplication.getInstance(), url);
        mRequstCloudErrorTask.start();
        mRequstCloudErrorTask.setListener(new CloudErrorListener());
        LogCat.e(TAG, "!!!!!!!!!!!!!!!!!!!requestCloudError start!!!!!!!!!!!!!!!!!!!");
    }

    /**
     * 请求云盘地址
     *
     * @param type
     */
    private void requestCloudPlay(String type) {
        mCurrCloudType = type;
        // 执行网盘相关请求
        if (null != mRequestCloudTask && !mRequestCloudTask.isCancelled()) {
            mRequestCloudTask.cancel();
        }
        mPlayStatusReport = new PlayStatusReporter();
        mPlayStatusReport.setAction(MoviesConstant.STATE_ACTION_PLAY);
        mPlayStatusReport.setPorder(mPlayEpisode.getPorder());
        mPlayStatusReport.setVid(mPlayEpisode.getCloudId());
        mPlayStatusReport.setExternal_id(mPlayEpisode.getExternalId());
        mPlayStatusReport.setGlobal_vid(mPlayEpisode.getGlobaVid());
        mPlayStatusReport.setSubsrc("nets");
        mPlayStatusReport.setSrartRequestTime(System.currentTimeMillis());
        mPlayStatusReport.setAid(mReportAid);
        if (mPlayData != null) {
            mPlayStatusReport.setVt(mPlayData.getVt());
        }

        mIsSdkPlayer = false;
        mRequestCloudTask = new RequestCloudDiskTask(MoviesApplication.getInstance());
        mRequestCloudTask.setParameter(mPlayEpisode.getCloudId(), type);
        mRequestCloudTask.setCurrClarity(lvideoVideoCode);
        mRequestCloudTask.setmListener(new CloudDiskRequestListener());
        mRequestCloudTask.start();
        LogCat.e(TAG, "!!!!!!!!!!!!!!!!!!!mRequestCloudTask start!!!!!!!!!!!!!!!!!!!");
        UmengEventPoster.doEventPost(UmengPostConstant.PlayVideo_nets); //播云盘源友盟上报
    }

    /**
     * 跳转至网页播放 zhangshuo 2014年5月4日 下午3:56:53
     */
    private void cloudDiskError() {
        if (mSelfOwnActivity != null && mSelfOwnActivity instanceof VideoDetailActivity) {
            if (mVideoViewPosition != null) {
                mVideoViewPosition.setVisibility(View.GONE);
            }
            if (mMediaController != null) {
                mMediaController.setVisibility(View.GONE);
            }
            ((VideoDetailActivity) mSelfOwnActivity).refreshToPlayError();
        }
    }

    /**
     * 跳转至网页播放 zhangshuo 2014年5月4日 下午3:56:53
     */
    private void jumpToWebPlayeActivity() {
        if (mIsPrepared) {
            reporterTime();
            selfReportPlayEnd();
            bigDataPlayReporter.onPlayEnd(); // 播放失败，end上报
        }
        // 进行播放失败的上报
        if (!mUMengReport.ismIsReported()) {
            // 设置失败
            mUMengReport.setIsUserH5("Yes");
            mUMengReport.setPlayresult(UmengEventPoster.PLAYER_RESULT_FAILED);
            mUMengReport.setmIsReported(true);
            UmengEventPoster.postPlayer(mUMengReport);
        }

        ToastUtil.showLongToast(mSelfOwnActivity, R.string.sniffer_failed);

        if (mSelfOwnActivity != null && mSelfOwnActivity instanceof VideoDetailActivity) {
            if (mVideoViewPosition != null) {
                mVideoViewPosition.setVisibility(View.GONE);
            }
            if (mMediaController != null) {
                mMediaController.setVisibility(View.GONE);
            }

            if (mPlayStatus != null) {
                mPlayStatus.setVisibility(View.GONE);
            }

            if (mRetryLinearLayout != null) {
                mRetryLinearLayout.setVisibility(View.VISIBLE);
            }
        }
    }

    private void setVideoUri(String playUrl) {
        if (!TextUtils.isEmpty(playUrl)) {

            mPlayStatusReport.setSetUrlTime(System.currentTimeMillis());

            mIsPrepared = false;
            if (mPlayContorl != null) {
                mPlayContorl.setVideoPath(playUrl);
            }
            bigDataPlayReporter.setUrl(playUrl);
            LogCat.e("wym", "setVideoUri() called and cur uuid " + bigDataPlayReporter.getUUID());
            bigDataPlayReporter.onPlayStart();
            if (!mIsPlayLocalUrl) {
                // 开始播放时暂停下载
                PlayerUtils.sendPlayingBroadcast(mSelfOwnActivity);
            }
        }
    }

    private void setPhotoUri(ArrayList<String> uri) {
//        if (uri != null && !TextUtils.isEmpty(uri.get(0)) && ((VideoViewPasterProxy)mPlayContorl).getAttachPhoto() != null) {
//            ImageLoader.getInstance().displayImage(uri.get(0), ((VideoViewPasterProxy)mPlayContorl).getAttachPhoto());
//        }

    }

    /**
     * 处理消息的handler
     */
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Utils.AD_SECOND:
                    if (mPlayContorl instanceof VideoViewPasterProxy) {
                        if (adSecond > 0) {
                            adSecond = adSecond - 1;
                            attachAdSecond.setText(" " + String.valueOf(adSecond));
                            ((VideoViewPasterProxy) mPlayContorl).setCurrentPosition(adSecond);
                            mHandler.sendEmptyMessageDelayed(Utils.AD_SECOND, 1000);
                        } else if (mPlayContorl != null && adSecond == 0 && ((VideoViewPasterProxy) mPlayContorl).isPlayingPhoto()){
                            ((VideoViewPasterProxy) mPlayContorl).complete();
                        }
                    }
                    break;
                case Utils.TOP_CONTROL:
                    count = 0;
                    firClick = 0;
                    secClick = 0;
                    showControllerLogic();
                    break;
                case Utils.TIME_REFRESH:
                    mTotalTime.setText(PlayerUtils.toStringTime((int) mDuration));
                    break;
                case Utils.TIME_REPORT:
                    if (mHandler != null) {
                        reporterTime();
                        if (mCurrentStep < SECOND_STEP) {
                            mHandler.sendEmptyMessageDelayed(Utils.TIME_REPORT, getNextStepTime());
                        } else {
                            if (mThirdReportTimer == null) {
                                mThirdReportTimer = new PlayerTimer(mHandler, Utils.TIME_REPORT);
                                Timer m_musictask = new Timer();
                                m_musictask.schedule(mThirdReportTimer, 0, INTERVAL_TIME);
                            }
                        }
                    }
                    break;
                case Utils.PROGRESS_CHANGE:
                    // 显示网速
                    showNetRate();
                    if (mIsPrepared) {
                        refreshPlaySeekBar();
                    }
                    mRealPlayTime++;
                    if(!mIsPlayLocalUrl){
                        //在线视频实际播放时长的umeng上报
                        if (mRealPlayTime == 180) {
                            mRealPlayMap.put("start", 3+"");
                            UmengEventPoster.doPost(UmengEventPoster.PLAYER_MAIN, mRealPlayMap);
                        }else if(mRealPlayTime == 300){
                            mRealPlayMap.put("start", 5+"");
                            UmengEventPoster.doPost(UmengEventPoster.PLAYER_MAIN, mRealPlayMap);
                        }else if(mRealPlayTime == 420){
                            mRealPlayMap.put("start", 7+"");
                            UmengEventPoster.doPost(UmengEventPoster.PLAYER_MAIN, mRealPlayMap);
                        }
                    }
                    break;
                // 控制栏消失
                case Utils.DISSMISS_MEDIACONTROLLER:
                    dissMissMediaControll(mIsFullScreen);
                    if (mPopupWindow.isShowing()) {
                        mPopupWindow.dismiss();
                    }
                    setLockScreenVisibile(false);
                    break;
                case Utils.DISSMISS_ALL_OVERLAYER:
                    mHandler.removeMessages(Utils.DISSMISS_ALL_OVERLAYER);
                    dissMissMediaControll(mIsFullScreen);
                    if (mPopupWindow.isShowing()) {
                        mPopupWindow.dismiss();
                    }
                    setLockScreenVisibile(false);
                    setPlayLoadingVisibile(false);
                    break;
                case Utils.VIDEO_DISMISS_GESTURE_POPUPWINDOW:
                    if (null != mGestureHandle) {
                        mGestureHandle.dismissGesturePopupWindow();
                        if(!mIsPlayLocalUrl && mIsBuffering){
                            showVideoLoading();
                            setPlayLoadingVisibile(true);
                        }
                    }
                    mHandler.sendEmptyMessageDelayed(
                            Utils.DISSMISS_MEDIACONTROLLER,
                            Utils.MEDIA_CONTROLLER_DISMISS_TIME);
                    break;
                case Utils.VIDEO_SHOW_CHANGE_CLARITY:
                    setMediaControllerTopVisibile(true);
                    setChangeClarityVisibile(true);
                    break;
                case Utils.GET_JS_RESULT:
                    LogUtils.e(Utils.TAG, "!!!!!!!!!!!!!!开始执行劫流逻辑");
                    mWebView.clearCache(true);
                    LogUtils.e(Utils.TAG, "　js send params : " + mSnifferParamter);
                    mWebView.loadUrl("javascript:TestJavaScriptInterface.startFunction(dealWithRequest('" + mSnifferParamter + "'));");
                    break;
                case Utils.DISSMISS_VIDEOSELECT_LIST:
                    break;
                default:
                    break;
            }
        }
    };

    private void resetSniffToIdle() {
        mSniffRetryCount = 0;
        mHandler.removeMessages(Utils.GET_JS_RESULT);
    }

    /**
     * 刷新播放进度条 zhangshuo 2014年4月28日 下午5:45:15
     */
    public void refreshPlaySeekBar() {
        if (null != mPlayContorl && null != mPlaySeekBar) {
            int oldTotalTime = 0;
            if (mStreamIndex > 0) {
                for (int i = 0; i < mStreamIndex; i++) {
                    if (mStreamListTime != null) {
                        if (i < mStreamListTime.size()) {
                            oldTotalTime += mStreamListTime.get(i);
                        }
                    }
                }
            }
            int currPosition = mPlayContorl.getCurrentPosition() + oldTotalTime;
            if (mDuration <= 0 && mPlayContorl.isPlaying()) {
                mDuration = mPlayContorl.getDuration();
            }
            long progress = mDuration <= 0 ? 0 : (PLAY_SEEKBAR_MAX
                    * currPosition / mDuration);
            mPlaySeekBar.setProgress((int) progress);
            if (null != mCurrTime) {
                String currTimeStr = PlayerUtils.toStringTime(currPosition);
                if (!TextUtils.isEmpty(currTimeStr)) {
                    mCurrTime.setVisibility(View.VISIBLE);
                    mCurrTime.setText(currTimeStr);
                } else {
                    mCurrTime.setVisibility(View.GONE);
                }
            }
        }
    }

    @Override
    public void onPrepared(MediaPlayer mp) {

        LogCat.e(TAG, "!!!!!!!!!onPrepared");
        LogUtils.e("wym", "onPrepared() init called and cur uuid " + bigDataPlayReporter.getUUID());
        if (null != mPlayContorl && !mIsPrepared) {
            mIsPrepared = true;
            if (mPlayContorl != null && mPlayContorl instanceof LVideoMediaPlayerControl && ((LVideoMediaPlayerControl) mPlayContorl).isSohuAdvertInPlayback()) {
                mMediaController.setVisibility(View.GONE);
                setPlayLoadingVisibile(false);
                mIsPrepared = false;
                mIsPlayingAdvertisement = true;
                if (mImgBack != null && Constants.SDK_TENCENT.equals(mPlayData.getPlayer()) && !TextUtils.isEmpty(mPlayEpisode.getExternalId())) {
                    // 如果是腾讯视频，播放广告时隐藏返回按钮
                    mImgBack.setVisibility(View.GONE);
                }
                return;
            } else {
                mIsPlayingAdvertisement = false;
                mMediaController.setVisibility(View.VISIBLE);
                setPlayLoadingVisibile(false);
                prepareTotalTime();
                if (mImgBack != null && mImgBack.getVisibility() == View.GONE) {
                    mImgBack.setVisibility(View.VISIBLE);
                }
            }
            // 设置当前播放时长*/
            mCurrTime.setText(PlayerUtils.toStringTime(mPlayContorl
                    .getCurrentPosition()));
            setPlayErrorLayoutVisibile(false);
            setPlayLoadingVisibile(false);
            setSelectClickable(true);
            // 取消切换清晰度提示
            mHandler.removeMessages(Utils.VIDEO_SHOW_CHANGE_CLARITY);
            setChangeClarityVisibile(false);
            // 影片缓冲成功展现整个控制栏并且5秒后消失
            showControllerLogic();
            startPlayer();
            startPlayTimeReport();// 第一次上报
            mRealPlayTime = 0;
            startPlayerTimer();

            setDataPlayTs(mCurrPlayTime);

            if (mPlayEpisode != null && mIsSdkPlayer) {
                mPlayStatusReport = new PlayStatusReporter();
                mPlayStatusReport.setAction(MoviesConstant.STATE_ACTION_PLAY);
                mPlayStatusReport.setPorder(mPlayEpisode.getPorder());
                mPlayStatusReport.setVid(mSnifferUrl);
                mPlayStatusReport.setExternal_id(mPlayEpisode.getExternalId());
                mPlayStatusReport.setGlobal_vid(mPlayEpisode.getGlobaVid());
                String reportSubsrc = TextUtils.isEmpty(mPlayEpisode.getSite()) ? mPlayData.getSite() : mPlayEpisode.getSite();
                mPlayStatusReport.setSubsrc(reportSubsrc + "sdk");
                mPlayStatusReport.setAid(mReportAid);
            }
            mPlayStatusReport.setVt(mPlayData.getVt());
            mPlayStatusReport.setStartPlayTime(System.currentTimeMillis());
            reportPlayState(MoviesConstant.PLAY_SUCCESS_STATE, "", "");
            if (mIsJSFailed) {
                reportPlayState(MoviesConstant.JS_ERROR_SERVER_PLAY_SUCCESS, "", "");
                mIsJSFailed = false;
            }
            bigDataPlayReporter.setDuration(mDuration); // 设置视频时长
            mPlayDataReport.setTotalTime(mDuration);
            if (PlayerUtils.SITE_CLOUDDISK.equals(mPlayData.getSite())
                    && mCurrPlayTime > 0) {
                mPlayContorl.seekTo(mCurrPlayTime);
            } else if (mIsNeedSeekByClarity && mCurrPlayTime > 0) {
                bigDataPlayReporter.onBufferEnd();
                mPlayContorl.seekTo(mCurrPlayTime);
                mIsNeedSeekByClarity = false;
            } else if (null != mPlayData.getmPlayRecord()
                    && mPlayData.getmPlayRecord().getSeekHistory() > 0
                    && (mStream_list == null || mStream_list.size() <= 1)) {
                mPlayContorl.seekTo((int) (mPlayData.getmPlayRecord()
                        .getSeekHistory()));
                mPlayPeriod.setRePlayTs((int) (mPlayData.getmPlayRecord()
                        .getSeekHistory()));
                bigDataPlayReporter.setProgress((int) (mPlayData
                        .getmPlayRecord().getSeekHistory()));
                bigDataPlayReporter.onBufferEnd();
            }
            else {
                bigDataPlayReporter.onBufferEnd();
            }
            PlayDataRecord record = MyDataRecordCreater.build(PlayDataRecord.class);
            record.setAcode(SelfDataConstant.AC_PLAY);
            record.setPlayac(SelfDataConstant.PLAYAC_PLAY);
            record.setAid(mPlayData.getAid());
            record.setPlayuuid(bigDataPlayReporter.getUUID());
            record.setName(mPlayData.getmViewName());
            record.setVt(mPlayData.getVt());
            record.setLabel(mPlayData.getSubcategoryname());
            record.setAreaname(mPlayData.getAreaname());
            record.setYear(mPlayData.getYear());
            record.setVlen(mDuration+"");
            record.setSite(mPlayData.getSite());
            record.setPt(mRealPlayTime +"");
            if(mPlayEpisode != null && mIsSdkPlayer){
                record.setPlayer("sdk");
            }
            if(PlayerUtils.SIET_LETV.equals(mPlayData.getSite())){
                if(0 == letvPlayStatus){
                    record.setPlayer("305");
                }else if(1 == letvPlayStatus){
                    record.setPlayer("sdk");
                }else {
                    record.setPlayer("");
                }
            }
            RealmDaoManager.addMyDataRecord(record);

            if (null != mGestureHandle) {
                mGestureHandle.showGestureGuideView(false);
            }
            if (mPlayContorl != null && mPlayContorl instanceof VideoViewBestvProxy) {
                mSohuDefinitionList = ((LVideoMediaPlayerControl) mPlayContorl).getSupportDefinitions();
                mClaritymap = DefinitionManager.getSupportDefMapOnlyOuter((ArrayList<Integer>) mSohuDefinitionList);
                setSohuPlayerDefinition(((LVideoMediaPlayerControl) mPlayContorl).getCurrentDefinition());
            }
            executeReportAfterPrepared();
        }
    }

    private void selfReportPlayInit(){
        PlayDataRecord record = MyDataRecordCreater.build(PlayDataRecord.class);
        record.setAcode(SelfDataConstant.AC_PLAY);
        record.setPlayac(SelfDataConstant.PLAYAC_INIT);
        record.setAid(mPlayData.getAid());
        record.setPlayuuid(bigDataPlayReporter.getUUID());
        record.setName(mPlayData.getmViewName());
        record.setVt(mPlayData.getVt());
        record.setLabel(mPlayData.getSubcategoryname());
        record.setAreaname(mPlayData.getAreaname());
        record.setYear(mPlayData.getYear());
        record.setSite(mPlayData.getSite());
        if(mPlayEpisode != null && mIsSdkPlayer){
            record.setPlayer("sdk");
        }
        if(PlayerUtils.SIET_LETV.equals(mPlayData.getSite())){
            if(0 == letvPlayStatus){
                record.setPlayer("305");
            }else if(1 == letvPlayStatus){
                record.setPlayer("sdk");
            }else {
                record.setPlayer("");
            }
        }
        RealmDaoManager.addMyDataRecord(record);
    }

    private void selfReportPlayEnd(){
        if(mPlayData != null){
            MyDataRecord record = MyDataRecordCreater.build(MyDataRecord.class);
            record.setAcode(SelfDataConstant.AC_PLAY);
            if(mPlayData != null && !TextUtils.isEmpty(mPlayData.getAid())){
                record.setAid(mPlayData.getAid());
            }
            record.setPlayac(SelfDataConstant.PLAYAC_END);
            record.setPt(mRealPlayTime +"");
            RealmDaoManager.addMyDataRecord(record);
        }
    }

    private void executeReportAfterPrepared() {
        if (mIsPlayLocalUrl) {
            return;
        }

        // 友盟上报
        if (null != mUMengReport && !mUMengReport.ismIsReported()) {
            mUMengReport.setIsUserH5("No");
            mUMengReport.setPlayresult(UmengEventPoster.PLAYER_RESULT_SUCCESS);
            UmengEventPoster.postPlayer(mUMengReport);
            mUMengReport.setmIsReported(true);
        }

        if ((PlayerUtils.SITE_CLOUDDISK.equals(mPlayData.getSite()) ||
                PlayerUtils.SIET_LETV.equals(mPlayData.getSite())) && mHandler != null) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    String errorUrl = mCDEManager.getmCdeHelper().getPlayErrorsUrl(mLinkShellUrl);
                    if (!TextUtils.isEmpty(errorUrl)) {
                        requestCloudError(errorUrl.replaceFirst("http://127.0.0.1", "http://" + Utils.getLocalIpAddress()));
                    }
                }
            }, 3000);
        }
    }

    private String getBufferTime() {
        StringBuffer bufferTime = new StringBuffer();
        if (mBufferTime <= 0) {
            mBufferTime = MIN_BUFFER_TIME;
            bufferTime.append(mBufferTime);
        } else if (mBufferTime > 0) {
            if (mBufferTime / 1000 > MAX_BUFFER_TIME) {
                mBufferTime = MAX_BUFFER_TIME;
                bufferTime.append(mBufferTime);
            } else if (mBufferTime / 1000 == 0) {
                bufferTime.append("0." + mBufferTime % 1000);
            } else {
                bufferTime.append(mBufferTime / 1000);
                if (mBufferTime % 1000 > 0) {
                    bufferTime.append("." + mBufferTime % 1000);
                }
            }
        }
        return bufferTime.toString();
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {

    }

    @Override
    public void onAdFinished() {
        if (Constants.SDK_TENCENT.equals(mPlayData.getPlayer()) && !TextUtils.isEmpty(mPlayEpisode.getExternalId())) {
            // 腾讯广告返回按钮
            if (mSelfOwnActivity != null) {
                if (mSelfOwnActivity instanceof VideoDetailActivity) {
                    ((VideoDetailActivity) mSelfOwnActivity).exitPlay();
                }
            }
        } else if ((mPlayContorl instanceof VideoViewPasterProxy) && ((VideoViewPasterProxy)mPlayContorl).isPlayingAd()) {
            playVideoAfterAd();
        } else {
            mPlayAd = false;
            bigDataPlayReporter.onAdEnd();
        }
    }

    public void playVideoAfterAd() {
        try {
            if (mPlayEpisode != null) {
                mPlayEpisode.setAdPlayed(true);
            }
            if (Constants.SDK_LETV.equals(mPlayData.getPlayer()) && !TextUtils.isEmpty(mPlayEpisode.getExternalId()) && 1 == MoviesConstant.letvPlayStatus) {
                if (mSelfOwnActivity == null) {
                    return;
                }
                doLetvSdkPlay();
            } else if (Constants.SDK_PPTV.equals(mPlayData.getPlayer()) && !TextUtils.isEmpty(mPlayEpisode.getExternalId())) {
                if (mSelfOwnActivity == null) {
                    return;
                }
                doPptvSdkPlay();
            } else {
                mIsPlayingAdvertisement = false;
                if (mSelfOwnActivity == null) {
                    return;
                }
                doTruePlay();
            }
            attachAdLinearLayout.setVisibility(View.GONE);
            attachAdBottomLinearLayout.setVisibility(View.GONE);
            setSound(false);
        } catch (Exception e) {

        }
    }

    @Override
    public void onAdLoading() {
        if ((mPlayContorl instanceof VideoViewPasterProxy) && ((VideoViewPasterProxy)mPlayContorl).isPlayingAd() && !mIsPlayingAdvertisement) {
            setPlayLoadingVisibile(false);
            if (((VideoViewPasterProxy) mPlayContorl).isPlayingPhoto()) {
                sound.setVisibility(View.GONE);
            } else {
                mPlayContorl.start();
            }
            attachAdLinearLayout.setVisibility(View.VISIBLE);
            attachAdBottomLinearLayout.setVisibility(View.VISIBLE);
            mIsPlayingAdvertisement = true;
            if (!((VideoViewPasterProxy) mPlayContorl).isPlayingPhoto()) {
                String sec = " " + ((HzPayload) mPasterAd.payload).ad.duration;
                attachAdSecond.setText(sec);
                adSecond = Integer.valueOf(((HzPayload) mPasterAd.payload).ad.duration);
                mHandler.removeMessages(Utils.AD_SECOND);
                mHandler.sendEmptyMessageDelayed(Utils.AD_SECOND, 1000);
            } else {
                String sec = " " + 5;
                attachAdSecond.setText(sec);
                adSecond = 5;
                mHandler.removeMessages(Utils.AD_SECOND);
                mHandler.sendEmptyMessageDelayed(Utils.AD_SECOND, 1000);
            }
            HashMap<String, String> gdtPropertyMap = new HashMap<>();
            if (mPlayData != null) {
                gdtPropertyMap.put("source", mPlayData.getSite());
            }
            if ("1".equals(((HzPayload)mPasterAd.payload).ad.action)) {
                gdtPropertyMap.put("ad_type", "h5");
            } else {
                gdtPropertyMap.put("ad_type", "download");
            }
            ArrayList<String> adShowReportUrls = ((HzPayload)mPasterAd.payload).ad.imp;
            if(adShowReportUrls != null && adShowReportUrls.size() > 0){
                for (int i=0;i<adShowReportUrls.size();i++){
                    if(!TextUtils.isEmpty(adShowReportUrls.get(i))){
                        new ThirdAdReportTask(MoviesApplication.getInstance(), adShowReportUrls.get(i)).start();
                    }
                }
            }
            UmengEventPoster.doPost(UmengEventPoster.HZPREROLLS_SHOW, gdtPropertyMap);
        }
    }

    @Override
    public void onAdSizeChanged(int width, int height) {

    }

    @Override
    public void onAdError(int what, int extra) {

    }

    @Override
    public void onAdStarted() {
        mPlayAd = true;
        bigDataPlayReporter.onAdStart();
        mIsPlayingAdvertisement = true;
        mHandler.sendEmptyMessage(Utils.DISSMISS_ALL_OVERLAYER);
    }

    /**
     * 播放器播放过程中的异常处理
     */
    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        showErrorCodeForDebug(what,null);
        if(mPlayEpisode != null && mIsSdkPlayer){
            mPlayStatusReport = new PlayStatusReporter();
            mPlayStatusReport.setAction(MoviesConstant.STATE_ACTION_PLAY);
            mPlayStatusReport.setPorder(mPlayEpisode.getPorder());
            mPlayStatusReport.setVid(mSnifferUrl);
            mPlayStatusReport.setExternal_id(mPlayEpisode.getExternalId());
            mPlayStatusReport.setGlobal_vid(mPlayEpisode.getGlobaVid());
            String reportSubsrc = TextUtils.isEmpty(mPlayEpisode.getSite()) ? mPlayData.getSite() : mPlayEpisode.getSite();
            mPlayStatusReport.setSubsrc(reportSubsrc + "sdk");
            mPlayStatusReport.setAid(mReportAid);
            mPlayStatusReport.setVt(mPlayData.getVt());
            String errorInfo = "";
            if (mPlayContorl != null && mPlayContorl instanceof LVideoMediaPlayerControl) {
                if(((LVideoMediaPlayerControl)mPlayContorl).getFirstErrorCode() != 0){
                    errorInfo = errorInfo + "F" + ((LVideoMediaPlayerControl)mPlayContorl).getFirstErrorCode();
                }
            }
            if(what != 0){
                errorInfo = errorInfo + "S" + what;
            }
            if(extra != 0){
                errorInfo = errorInfo + "T" + extra;
            }
            if(!TextUtils.isEmpty(errorInfo)){
                mPlayStatusReport.setmErrorInfo(errorInfo);
            }
        }
        return onErrorPlayLogic(mp,what,extra,mIsSdkPlayer);
    }

    private boolean onErrorPlayLogic(MediaPlayer mp, int what, int extra,boolean issdkPlayer) {
        reportPlayState(MoviesConstant.PLAY_FAIL_STATE, "", "");
        if (mIsJSFailed) {
            reportPlayState(MoviesConstant.JS_ERROR_SERVER_PLAY_FAIL, "", "");
            mIsJSFailed = false;
        }
        if (mIsJSSuccessed) {
            reportPlayState(MoviesConstant.JS_SUCCESS_URL_PLAY_ERROR, "", "");
            mIsJSSuccessed = false;
        }
        boolean isLVideo = isLVideoSource();
        LogUtils.e(TAG, "!!!!!!mp!!!!" + mp + "!!!!!!what!!!!!" + what
                + "!!!!!extra!!!!!!" + extra);
        LogCat.e(TAG, "!!!!!!mp!!!!" + mp + "!!!!!!what!!!!!" + what
                + "!!!!!extra!!!!!!" + extra);
        if ((PlayerUtils.SITE_CLOUDDISK.equals(mPlayData.getSite()) ||
                (PlayerUtils.SIET_LETV.equals(mPlayData.getSite())) && 0 == MoviesConstant.letvPlayStatus) && mHandler != null) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    String errorUrl = mCDEManager.getmCdeHelper().getPlayErrorsUrl(mLinkShellUrl);
                    if (!TextUtils.isEmpty(errorUrl)) {
                        requestCloudError(errorUrl.replaceFirst("http://127.0.0.1", "http://" + Utils.getLocalIpAddress()));
                    }
                }
            }, 3000);
        }
        // 出错时首先保存播放历史
        mCurrPlayTime = getCurrPosition();
        mPlayDataReport.setErrorReTs(mCurrPlayTime);
        savePlayRecord(mCurrPlayTime);
        // 注销错误监听
        if (mPlayContorl != null) {
            mPlayContorl.setOnErrorListener(null);
        }
        // 停止播放器计时
        stopPlayerTimer();
        mRealPlayTime = 0;
        stopTimeCircleReport();
        // 如果当前是本地视频则创建错误提示框
        if (mIsPlayLocalUrl) {
            bigDataPlayReporter.onPlayError(isLVideo, BigDataConstants.LOCAL_PLAY_ERR);
            DialogUtil.createSingBtnDialog(mSelfOwnActivity,
                    R.string.playlocalfilerror, false, mDialogOnClickListener,
                    mDialogOnKeyListener);
        } else {
            LogUtils.e(Utils.TAG, "!!!!!!!onError!!!!!!! onlinePlay err");
            bigDataPlayReporter.onPlayError(isLVideo, BigDataConstants.ONLINE_PLAY_ERR);
            mCloudPlayPosition = 0;
            if (null != mPlayContorl) {
                mPlayContorl.stopPlayback();
                mPlayContorl = null;
                PlayerUtils.DEFAULT_PLAYER_TYPE = PlayDecodeMananger.getCurrPlayerType();
            }
            setControllerUI();
            if (mIsPrepared && mCurrPlayTime > PLAY_SUCCESS_POSITION_MIN) {
                LogUtils.e(Utils.TAG, "!!!!!!!onError!!!!!!! onlinePlay process err");
                if (mReplayNum < REPLAY_MAX) {
                    ++mReplayNum;
                    // 如果当前已经播放成功则重新加载
                    mIsAllowLetvSdk = false;
                    executeProcessBySite(mPlayData.getSite());
                } else {
                    mReplayNum = 0;
                    bigDataPlayReporter.onPlayError(isLVideo, BigDataConstants.PLAY_OTHER_ERR);
                    jumpToWebPlayeActivity();
                }
            } else {                LogUtils.e(Utils.TAG, "!!!!!!!onError!!!!!!! onlinePlay prestart err");
                // 如果刚开始播放就出错
                String site = mPlayData.getSite();
                if (!TextUtils.isEmpty(site)) {
                    // 如果当前站点是乐视站内源
                    if (PlayerUtils.SIET_LETV.equals(site) && "0".equals(SharePreferenceManager.getVaule(mSelfOwnActivity, SharePreferenceManager.FAILOVERPLAYTYPE, "1"))) {
                        handleLeTvError(site);
                    } else if (PlayerUtils.SITE_CLOUDDISK.equals(site)) {
                        handleCloudDiskError();
                    } else {
                        if (mPlayEpisode != null && issdkPlayer) {
                            if (Constants.SDK_BESTV.equals(mPlayData.getPlayer())) {
                                jumpToWebPlayeActivity();
                            } else {
                                executeOutSiteProcess();
                            }
                        } else {
                            // TODO 地址仍不能正常播放 调用update接口
                            LogUtils.e(Utils.TAG, "!!!!!!!onError!!!!!!! onlinePlay outsite changeStream ");
                            // 切换其他清晰度
                            mCurStreamIndex++;
                            doPlayLogic2(mCurStreamIndex);
                            // update操作
                            excuteUpdatestreamTask();
//                        handlerOutSiteError();
                        }
                    }
                } else {
                    bigDataPlayReporter.onPlayError(isLVideo, BigDataConstants.FILE_NOT_LEGAL_ERR);
                    jumpToWebPlayeActivity();
                }
            }
        }
        return false;
    }

    private void handleLeTvError(String site) {
        if( 0 == letvPlayStatus){
            if (!PlayDecodeMananger.ismNeedSysDecoder()) {
                // 设置当前需要系统硬解
                PlayDecodeMananger.setmNeedSysDecoder(true);
                excuteLetvProcess();
            } else {
                bigDataPlayReporter.onPlayError(true, BigDataConstants.PLAY_OTHER_ERR);
                jumpToWebPlayeActivity();
            }
        }else{
            excuteLetvProcess();
        }
    }

    /**
     * 处理云盘错误 zhangshuo 2014年10月10日 下午3:19:53
     */
    private void handleCloudDiskError() {
        if (!PlayDecodeMananger.ismNeedSysDecoder()) {
            PlayDecodeMananger.setmNeedSysDecoder(true);
            String cloudType = PlayDecodeMananger.getCloudSourceType();
            requestCloudPlay(cloudType);
        } else {
            bigDataPlayReporter.onPlayError(true, BigDataConstants.PLAY_URL_ERR);
            cloudDiskError();
        }
    }

    /**
     * 退出的Dialog监听
     *
     * @author zhangshuo
     */
    private class ExitDialogOnClickListener implements
            DialogInterface.OnClickListener {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
            exit();
        }
    }

    private class ExitOnKeyListener implements DialogInterface.OnKeyListener {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            LogUtils.e(TAG, "!!!!ExitOnKeyListener!!!!!!!");
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                dialog.dismiss();
                exit();
            }
            return false;
        }
    }

    private void exit() {
        // 如果所有影片播放均完成则推出当前播放器
        resetPlayData();
        mSelfOwnActivity.finish();
        mSelfOwnActivity.unregisterReceiver(timeReceiver);
        mSelfOwnActivity.unregisterReceiver(batteryChangedReceiver);
    }

    /**
     * 设置播放下一集的状态 zhangshuo 2014年7月3日 下午4:37:49
     */
    private void playNext() {
        LogUtils.e("wym", "playNext() next called and cur uuid " + bigDataPlayReporter.getUUID());
        mStreamIndex = 0;
        mIsFirstTime = true;
        isFirstDragReported = false;
        selfReportPlayEnd();
        bigDataPlayReporter.onPlayEnd();// 手动切换剧集上报end动作
        bigDataPlayReporter.resetUUID();
        int size = 0;
        // 将当前位置向下移动一位
        ++mVideoPosition;
        executeChangePrepared();
        // 如果当前播放的是本地文件
        if (mIsPlayLocalUrl) {
            executeLocalChangePlay();
            size = mLocalPlayLists.size();
        } else {
            // 获取当前位置的porder
            String porder = mPorderList.get(mVideoPosition);
            if (!TextUtils.isEmpty(porder)) {
                Episode episode = findEpisodeByPorder(porder);
                if (null != episode) {
                    mPlayDataReport = new PlayDataReporter();
                    if (PlayerUtils.SITE_CLOUDDISK.equals(mPlayData.getSite())) {
                        lvideoVideoCode = PlayerUtils.PLS_MP4_350;  //云盘切集之后重置清晰度
                    }
                    ischangeClarity = false;
                    mIsAllowLetvSdk = true;
                    executeCommonPlay(episode);
                    if (mSelfOwnActivity != null && mSelfOwnActivity instanceof VideoDetailActivity) {
                        ((VideoDetailActivity) mSelfOwnActivity).updateEpisodeStatus(mVideoPosition);
                    }
                } else {
                    ++mCurrPage;
                    // 请求分页数据，并顺序的添加在list末尾
                    requestPageInfos(PlayerUtils.END);
                }
            } else {
                --mVideoPosition;
                return;
            }
            size = mPlayData.getmPorderLists().size();
        }
        setNextState(size);
    }

    private void setNextState(int size) {
        if (++mVideoPosition >= size) {
            mPlayNextBtn.setEnabled(false);
        } else {
            mPlayNextBtn.setEnabled(true);
        }
        mVideoPosition = mVideoPosition - 1;
    }

    private void executeLocalChangePlay() {
        if (mVideoPosition < mLocalPlayLists.size()) {
            LocalVideoEpisode localVideoEpisode = mLocalPlayLists.get(mVideoPosition);
            // 存储播放历史
            executeLocalPlayLogic(localVideoEpisode);
        }
    }

    /**
     * 切换清晰度准备工作
     */
    private void executeClarityChangePlay() {
        if (mEpisodes != null) {
            Episode episode = mEpisodes.get(mVideoPosition);
            // 需要初始化嗅探上报
            resetReportData();
            resetPlayData();
            isInPlayingProcess = false;
            setControllerUI();
            mIsNeedSeekByClarity = true;
            // savePlayRecord(0);//??不调用，然后需要保存seek
            isFirstDragReported = false;
            mIsAllowLetvSdk = false;
            executeCommonPlay(episode);
        }
    }

    /**
     * 切换剧集准备工作
     */
    private void executeChangePrepared() {
        resetOutSiteData(); //重置外网播放逻辑数据
        mInSiteRetryTime = 0; //切换剧集需重置
        mIsNeedSeekByClarity = false;
        mCurrPlayTime = 0;
        // 切换至下一集前需要初始化嗅探上报
        resetReportData();
        resetPlayData();
        setControllerUI();
        savePlayRecord(0);
        if (mIsPlayLocalUrl) {
            if (null != mLocalAdapter) {
                mLocalAdapter.setmSelectProder(mLocalPlayLists.get(mVideoPosition).getPorder());
                mLocalAdapter.notifyDataSetChanged();
            }
        }
    }

    /**
     * 播放完成状态
     */
    @Override
    public void onCompletion(MediaPlayer mp) {
        if (mStream_list != null && mStream_list.size() > 1
                && mStreamIndex < mStream_list.size() - 1) {
            mStreamIndex++;
            if (!mIsPlayLocalUrl) {
                doPlay(PlayerUtils.DEFAULT_PLAYER_TYPE, mStream_list.get(mStreamIndex));
            } else {
                doPlayLocalVideo(mStream_list.get(mStreamIndex));
            }
            return;
        }
        if (mPlayNextBtn.isEnabled()) {
            savePlayRecord(getCurrPosition() > 5000 ? getCurrPosition() - 5000 : 0);
            setDataPauseTs(getCurrPosition());
            String uploadPlayData = mPlayDataReport.toString();
            new ReportPlaySessionTask(MoviesApplication.getInstance(), uploadPlayData).start();
            // 心跳上报时机
            reporterTime();
            bigDataPlayReporter.onPlayFinish(); //自然播放完上报
            stopTimeCircleReport();
            playNext();
        } else {
            setDataPauseTs(getCurrPosition());
            String uploadPlayData = mPlayDataReport.toString();
            new ReportPlaySessionTask(MoviesApplication.getInstance(), uploadPlayData).start();
            savePlayRecord(getCurrPosition() > 5000 ? getCurrPosition() - 5000 : 0);
            // 心跳上报时机
            reporterTime();
            selfReportPlayEnd();
            bigDataPlayReporter.onPlayEnd(); // 成功退出
            bigDataPlayReporter.onPlayFinish();
            // 如果所有影片播放均完成则推出当前播放器
            resetPlayData();
            mSelfOwnActivity.finish();
            // 播放完成时可以开启下载
            PlayerUtils.sendNotPlayingBroadcast(mSelfOwnActivity);
        }
    }

    private void resetReportData() {
        // 切换下一集之前上报数据需要清除
        mUMengReport.resetData();
        if (null != mStateList) {
            mStateList.clear();
        }
    }

    /**
     * 重置播放器相关数据 zhangshuo 2014年5月4日 上午10:20:17
     */
    public void resetPlayData() {
        resetDataState();
        if (null != mPlayContorl) {
            mPlayContorl.stopPlayback();
            mPlayContorl = null;
        }
        stopCdeSource();
    }

    public void releaseData() {
        releaseList();
        releaseMap();
        releaseWebView();
        unRegisterReceiver();
    }

    private void releaseWebView() {
        if (null != mWebView) {
            mWebView.clearCache(true);
            mWebView.removeAllViews();
            mWebView.destroyDrawingCache();
        }
        setConfigCallback(null);
    }

    /**
     * WebView防止内存泄露
     *
     * @param windowManager zhangshuo 2014年12月25日 下午5:38:12
     */
    public void setConfigCallback(WindowManager windowManager) {
        if (windowManager == null) return;
        try {
            Field field = WebView.class.getDeclaredField("mWebViewCore");
            field = field.getType().getDeclaredField("mBrowserFrame");
            field = field.getType().getDeclaredField("sConfigCallback");
            field.setAccessible(true);
            Object configCallback = field.get(null);
            if (null == configCallback) {
                return;
            }
            field = field.getType().getDeclaredField("mWindowManager");
            field.setAccessible(true);
            field.set(configCallback, windowManager);
        } catch (Exception e) {

        }
    }

    private void releaseList() {
        if (null != mEpisodes) {
            mEpisodes.clear();
            mEpisodes = null;
        }

        if (null != mCloudPlayUrls) {
            mCloudPlayUrls.clear();
            mCloudPlayUrls = null;
        }

        if (null != mLocalPlayLists) {
            mLocalPlayLists.clear();
            mLocalPlayLists = null;
        }
    }

    private void releaseMap() {
        if (null != mApiMap) {
            mApiMap.clear();
            mApiMap = null;
        }

        if (null != mRuleMap) {
            mRuleMap.clear();
            mRuleMap = null;
        }

        if (null != mPlayUrlMap) {
            mPlayUrlMap.clear();
            mPlayUrlMap = null;
        }
    }

    public void onUserFinish() {
        setDataPauseTs(mCurrPlayTime);
        String uploadPlayData = mPlayDataReport.toString();
        new ReportPlaySessionTask(MoviesApplication.getInstance(), uploadPlayData).start();
        if (mIsPrepared) {
            reporterTime();
            selfReportPlayEnd();
            if (isBigDataInit) {
                bigDataPlayReporter.onPlayEnd();
                isBigDataInit = false;
            }
        }
        if (mPlayContorl != null && mPlayContorl instanceof LVideoMediaPlayerControl && ((LVideoMediaPlayerControl) mPlayContorl).isSohuAdvertInPlayback()) {
            // 第三方SDK播放广告
            reportPlayState(MoviesConstant.NOPALY_AD_EXIT_STATE, "", "");
        } else if (mPlayStatusReport.getSetUrlTime() != 0 && mPlayStatusReport.getStartPlayTime() == 0) {
            reportPlayState(MoviesConstant.NOPALY_EXIT_STATE, "", "");
        }
        stopTimeCircleReport();
    }

    private void resetPlayerData() {
        mIsPause = false;
        mIsPrepared = false;
        mIsControllerShow = false;
        // 重试次数置为0
        mReplayNum = 0;
        // 重置云盘播放位置
        mHandler.removeMessages(Utils.DISSMISS_MEDIACONTROLLER);
    }

    private void resetDataState() {
        resetSniffToIdle();
        mCurrPlayState = null;
        mIsPause = false;
        mIsPrepared = false;
        mIsControllerShow = false;
        // 重试次数置为0
        mReplayNum = 0;
        // 重置云盘播放位置
        mCloudPlayPosition = 0;
        // 设置默认使用M3u8播放片源
        PlayDecodeMananger.setmNeedSysDecoder(false);
        mHandler.removeMessages(Utils.DISSMISS_MEDIACONTROLLER);
        stopPlayerTimer();
        mRealPlayTime = 0;
        stopTimeCircleReport();
    }

    /**
     * 获取影片名称 zhangshuo 2014年5月2日 下午10:32:11
     */
    private String getVideoName(Episode episode) {
        StringBuffer nameBuff = new StringBuffer();

        if (!TextUtils.isEmpty(episode.getName())) {
            nameBuff.append(episode.getName());
        }
        return nameBuff.toString();
    }

    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        LogUtils.e(TAG, "!!!!onInfo!!!!what!!" + what);
        switch (what) {
            case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                LogUtils.e(TAG, "!!!!onInfo!!!!!!MEDIA_INFO_BUFFERING_START");
                mIsBuffering = true;
                bufferStart(getCurrPosition());
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                LogUtils.e(TAG, "!!!!onInfo!!!!!!MEDIA_INFO_BUFFERING_END");
                mIsBuffering = false;
                bufferEnd();
            case MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING:
                LogUtils.e(TAG, "!!!!onInfo!!!!!!MEDIA_INFO_VIDEO_TRACK_LAGGING");
                break;
            case MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
                LogUtils.e(TAG, "!!!!onInfo!!!!!!MEDIA_INFO_BAD_INTERLEAVING");
                break;
            case MediaPlayer.MEDIA_INFO_NOT_SEEKABLE:
                LogUtils.e(TAG, "!!!!onInfo!!!!!!MEDIA_INFO_NOT_SEEKABLE");
                break;
            case MyPlayerConstant.START_TO_PLAY:
                updatePlayBtnBg(false);
                setPlayLoadingVisibile(false);
                break;
            default:
                break;
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        mHandler.removeMessages(Utils.DISSMISS_MEDIACONTROLLER);
        switch (v.getId()) {
            case R.id.show_device_iv:
                break;
            case R.id.btn_play_next:
                setDataPauseTs(mCurrPlayTime);
                String uploadPlayData = mPlayDataReport.toString();
                new ReportPlaySessionTask(MoviesApplication.getInstance(), uploadPlayData).start();
                playNext();
                if(pauseAdLayout != null){
                    pauseAdLayout.setVisibility(View.GONE);
                }
                break;
            case R.id.center_play_iv:
            case R.id.btn_play:
                clickPauseOrPlay();
                mHandler.sendEmptyMessageDelayed(Utils.DISSMISS_MEDIACONTROLLER,
                        Utils.MEDIA_CONTROLLER_DISMISS_TIME);
                break;
            case R.id.videoplayer_error_icon:
                int netType = NetWorkTypeUtils.reportNetType(MoviesApplication.getInstance());
                if (netType == NetWorkTypeUtils.NETTYPE_NO || netType == NetWorkTypeUtils.TYPE_ERROR) {
                    return;
                }
                setControllerUI();
                setVideoUri(mCurrentPlayingUrl);
                break;
            // 用户点击锁屏按钮
            case R.id.videoplayer_lockscreen:
                boolean isSelected = mLockScreenBtn.isSelected();
                mLockScreenBtn.setSelected(!isSelected);
                // 如果当前是锁屏状态则
                if (isSelected) {
                    showMediaControll(mIsFullScreen);
                } else {
                    dissMissMediaControll(mIsFullScreen);
                }
                mHandler.sendEmptyMessageDelayed(Utils.DISSMISS_MEDIACONTROLLER,
                        Utils.MEDIA_CONTROLLER_DISMISS_TIME);
                break;
            case R.id.episode_select_tv:
                selectUiChange();
                setFloorControllerGone();
                mHandler.sendEmptyMessageDelayed(Utils.DISSMISS_MEDIACONTROLLER,
                        Utils.MEDIA_CONTROLLER_DISMISS_TIME);
                if(pauseAdLayout != null){
                    pauseAdLayout.setVisibility(View.GONE);
                }
                LogUtils.e("wym", "tv_select select called and cur uuid " + bigDataPlayReporter.getUUID());
                break;
            case R.id.clarity_select_tv:
                if (null != mClarityPopupWindow) {
                    if ("letv".equalsIgnoreCase(mPlayData.getSite())
                            || TextUtils.equals(PlayerUtils.SITE_CLOUDDISK , mPlayData.getSite())) {
                        if ((mPlayData.getPlayer().equals(Constants.SDK_LETV) && 1 == MoviesConstant.letvPlayStatus) || ("letv".equalsIgnoreCase(mPlayData.getSite()) && 2 == MoviesConstant.letvPlayStatus)) {
                            mClarityPopupWindow.showOutsitePopView();
                        } else {
                            mClarityPopupWindow.showPopView(mClaritymap, lvideoVideoCode,mPlayData.getPlayer());
                        }
                    } else if (PlayerUtils.isOutSite(mPlayData.getSite())) {
                        mClarityPopupWindow.showOutsitePopView();
                    }
                    setFloorControllerGone();
                    if(pauseAdLayout != null){
                        pauseAdLayout.setVisibility(View.GONE);
                    }
                }
                break;
            case R.id.change_clarity:
                if (!DefinitionManager.isDefinitionFluency(lvideoVideoCode)) {
                    changeLetvDefinition(DefinitionManager.DEFINITION_TYPE_FLUENCY
                            , PlayerUtils.VT_MP4);
                    setChangeClarityVisibile(false);
                } else {
                    // 偶尔会出现
                    setChangeClarityVisibile(false);
                }
                break;

            case R.id.iv_ad_switch_screen:
            case R.id.switch_screen_iv:
                onFullScreen();
                break;

            case R.id.tv_attach_ad_skip:
                HashMap<String, String> gdtPropertyMap = new HashMap<>();
                gdtPropertyMap.put("position", "pre-roll");
                UmengEventPoster.doPost(UmengEventPoster.GDTAD_CLOSE, gdtPropertyMap);
                playVideoAfterAd();
                break;
            case R.id.player_ad_count_and_skip:
                PPTVSdkMgr.getInstance().skipAd(); //跳过广告暂时无效
                break;
            case R.id.player_ad_view:
                PPTVSdkMgr.getInstance().playAdDetail();
                break;

            case R.id.iv_attach_ad_sound:
                clickPlayerSound();
                break;

            default:
                break;
        }
    }

    private void clickPlayerSound() {
        if (mPlayContorl != null) {
            AudioManager mAudioManager = (AudioManager) mSelfOwnActivity.getSystemService(Context.AUDIO_SERVICE);
            if (soundClose) {
                mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC , false);
                soundClose = false;
                sound.setImageResource(R.drawable.on_sound);
            } else {
                mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC , true);
                soundClose = true;
                sound.setImageResource(R.drawable.off_sound);
            }
        }
    }

    private void setSound(boolean close) {
        AudioManager mAudioManager = (AudioManager) mSelfOwnActivity.getSystemService(Context.AUDIO_SERVICE);
        if (close) {
            mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC , true);
            soundClose = true;
            sound.setImageResource(R.drawable.off_sound);
        } else {
            mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC , false);
            soundClose = false;
            sound.setImageResource(R.drawable.on_sound);
        }
    }

    private void onFullScreen() {
        if (UIs.isScreenOriatationPortrait(mSelfOwnActivity)) {
            ((VideoDetailActivity) mSelfOwnActivity).setFullScreenByClick(true, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            ((VideoDetailActivity) mSelfOwnActivity).setFullScreenByClick(false, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    /**
     * 清晰度切换监听事件
     */
    private OnClickListener changeClarityListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            String site = TextUtils.isEmpty(mPlayEpisode.getSite()) ? mPlayData.getSite(): mPlayEpisode.getSite();
            if(mIsSdkPlayer){
                if (null != mClarityPopupWindow
                        && mClarityPopupWindow.getmSiftPopupWindow().isShowing()) {
                    mClarityPopupWindow.getmSiftPopupWindow().dismiss();
                }
                if (mPlayContorl instanceof LVideoMediaPlayerControl) {
                    String currentDef = String.valueOf(((LVideoMediaPlayerControl) mPlayContorl).getCurrentDefinition());
                    switch (v.getId()) {
                        case R.id.definition_super:
                            if (!DefinitionManager.isDefinitionSuper(currentDef)) {
                                changeOuterDefinition2(DefinitionManager.DEFINITION_TYPE_SUPER, PlayerUtils.VT_MP4_720P);
                            }
                            break;
                        case R.id.definition_highclear:
                            if (!DefinitionManager.isDefinitionHigh(currentDef)) {
                                changeOuterDefinition2(DefinitionManager.DEFINITION_TYPE_HIGH, PlayerUtils.VT_MP4_720p_db);
                            }
                            break;
                        case R.id.definition_common:
                            if (!DefinitionManager.isDefinitionNormal(currentDef)) {
                                changeOuterDefinition2(DefinitionManager.DEFINITION_TYPE_NORMAL, PlayerUtils.VT_MP4_350);
                            }
                            break;
                        case R.id.definition_fluency:
                            if (!DefinitionManager.isDefinitionFluency(currentDef)) {
                                changeOuterDefinition2(DefinitionManager.DEFINITION_TYPE_FLUENCY, PlayerUtils.VT_MP4);
                            }
                            break;
                    }
                }
            } else if (mPlayData != null && (PlayerUtils.isOutSite(site) || ("letv".equals(site) && 2 == MoviesConstant.letvPlayStatus))) {
                if (null != mClarityPopupWindow
                        && mClarityPopupWindow.getmSiftPopupWindow().isShowing()) {
                    mClarityPopupWindow.getmSiftPopupWindow().dismiss();
                }
                retryTime = 0; //切换清晰度也需重置
                mIsNeedSeekByClarity = true;
                switch (v.getId()) {
                    case R.id.definition_super:
                        if (!DefinitionManager.isDefinitionSuper(mOutsiteClarity)) {
                            ischangeClarity = true;
                            changeOuterDefinition(DefinitionManager.DEFINITION_TYPE_SUPER, PlayerUtils.VT_MP4_720P);
                        }
                        break;
                    case R.id.definition_highclear:
                        if (!DefinitionManager.isDefinitionHigh(mOutsiteClarity)) {
                            ischangeClarity = true;
                            changeOuterDefinition(DefinitionManager.DEFINITION_TYPE_HIGH, PlayerUtils.VT_MP4_720p_db);
                        }
                        break;
                    case R.id.definition_common:
                        if (!DefinitionManager.isDefinitionNormal(mOutsiteClarity)) {
                            ischangeClarity = true;
                            changeOuterDefinition(DefinitionManager.DEFINITION_TYPE_NORMAL, PlayerUtils.VT_MP4_350);
                        }
                        break;
                    case R.id.definition_fluency:
                        if (!DefinitionManager.isDefinitionFluency(mOutsiteClarity)) {
                            ischangeClarity = true;
                            changeOuterDefinition(DefinitionManager.DEFINITION_TYPE_FLUENCY, PlayerUtils.VT_MP4);
                        }
                        break;
                }
            } else if (TextUtils.equals(PlayerUtils.SITE_CLOUDDISK , mPlayData.getSite())) {
                if (null != mClarityPopupWindow
                        && mClarityPopupWindow.getmSiftPopupWindow()
                        .isShowing()) {
                    mClarityPopupWindow.getmSiftPopupWindow().dismiss();
                }
                switch (v.getId()) {
                    case R.id.definition_super: {
                        if (!DefinitionManager.isDefinitionSuper(lvideoVideoCode)) {
                            ischangeClarity = true;
                            changeCloudDefinition(DefinitionManager.DEFINITION_TYPE_SUPER, PlayerUtils.VT_MP4_720P);
                        }
                        break;
                    }
                    case R.id.definition_highclear:{
                        if (!DefinitionManager.isDefinitionHigh(lvideoVideoCode)) {
                            ischangeClarity = true;
                            changeCloudDefinition(DefinitionManager.DEFINITION_TYPE_HIGH, PlayerUtils.VT_MP4_720p_db);
                        }
                        break;
                    }
                    case R.id.definition_common:{
                        if (!DefinitionManager.isDefinitionNormal(lvideoVideoCode)) {
                            ischangeClarity = true;
                            changeCloudDefinition(DefinitionManager.DEFINITION_TYPE_NORMAL, PlayerUtils.VT_MP4_350);
                        }
                        break;
                    }
                    case R.id.definition_fluency:{
                        if (!DefinitionManager.isDefinitionFluency(lvideoVideoCode)) {
                            ischangeClarity = true;
                            changeCloudDefinition(DefinitionManager.DEFINITION_TYPE_FLUENCY, PlayerUtils.VT_MP4);
                        }
                        break;
                    }
                }
            }else {
                if (null != mClarityPopupWindow
                        && mClarityPopupWindow.getmSiftPopupWindow()
                        .isShowing()) {
                    mClarityPopupWindow.getmSiftPopupWindow().dismiss();
                }
                switch (v.getId()) {
                    case R.id.definition_super:
                        if (!DefinitionManager.isDefinitionSuper(lvideoVideoCode)) {
                            ischangeClarity = true;
                            changeLetvDefinition(DefinitionManager.DEFINITION_TYPE_SUPER
                                , PlayerUtils.VT_MP4_720P);
                        }
                        break;
                    case R.id.definition_highclear:
                        if (!DefinitionManager.isDefinitionHigh(lvideoVideoCode)) {
                            ischangeClarity = true;
                            changeLetvDefinition(DefinitionManager.DEFINITION_TYPE_HIGH
                                    , PlayerUtils.VT_MP4_720p_db);
                        }
                        break;
                    case R.id.definition_common:
                        if (!DefinitionManager.isDefinitionNormal(lvideoVideoCode)) {
                            ischangeClarity = true;
                            changeLetvDefinition(DefinitionManager.DEFINITION_TYPE_NORMAL
                                    , PlayerUtils.VT_MP4_350);
                        }
                        break;
                    case R.id.definition_fluency:
                        if (!DefinitionManager.isDefinitionFluency(lvideoVideoCode)) {
                            ischangeClarity = true;
                            changeLetvDefinition(DefinitionManager.DEFINITION_TYPE_FLUENCY
                                    , PlayerUtils.VT_MP4);
                        }
                        break;
                }
            }
        }
    };

    private void changeLetvDefinition(String defType,String vType) {
        lvideoVideoCode = DefinitionManager.getVideoCaseByDefType(videoCaseList
                , defType
                , lvideoVideoCode);
        mCurrPlayTime = getCurrPosition();
        LogUtils.e(TAG, "!!!!!!!!!!!!!!!!!!!!!切至超清 cur playPos is " + mCurrPlayTime);
        reporterTime();
        bigDataPlayReporter.onStreamChange(vType);

        MyDataRecord record = MyDataRecordCreater.build(MyDataRecord.class);
        record.setAcode(SelfDataConstant.AC_PLAY);
        if(mPlayData != null && !TextUtils.isEmpty(mPlayData.getAid())){
            record.setAid(mPlayData.getAid());
        }
        record.setPlayac(SelfDataConstant.PLAYAC_TG);
        record.setPt(mRealPlayTime +"");
        RealmDaoManager.addMyDataRecord(record);

        mInSiteRetryTime = 0; //切换清晰度也需重置
        DefinitionManager.DefinitionObj definitionObj = DefinitionManager.checkDefClassify(lvideoVideoCode);
        if (definitionObj != null) {
            mClarity_select.setText(definitionObj.showTextResId);
            bottomTips = mSelfOwnActivity.getResources().getString(definitionObj.showTextResId);
        }
        executeClarityChangePlay();
    }

    private void changeCloudDefinition(String defType,String vType) {
        lvideoVideoCode = DefinitionManager.getVideoCaseByDefType(videoCaseList
                , defType
                , lvideoVideoCode);
        mCurrPlayTime = getCurrPosition();
        reporterTime();
        bigDataPlayReporter.onStreamChange(vType);

        MyDataRecord record = MyDataRecordCreater.build(MyDataRecord.class);
        record.setAcode(SelfDataConstant.AC_PLAY);
        if(mPlayData != null && !TextUtils.isEmpty(mPlayData.getAid())){
            record.setAid(mPlayData.getAid());
        }
        record.setPlayac(SelfDataConstant.PLAYAC_TG);
        record.setPt(mRealPlayTime +"");
        RealmDaoManager.addMyDataRecord(record);

        DefinitionManager.DefinitionObj definitionObj = DefinitionManager.checkDefClassify(lvideoVideoCode);
        if (definitionObj != null) {
            mClarity_select.setText(definitionObj.showTextResId);
            bottomTips = mSelfOwnActivity.getResources().getString(definitionObj.showTextResId);
        }
        executeClarityChangePlay();
    }

    private void changeOuterDefinition2(String defType, String vType) {
        ArrayList<String> stringArrayList = new ArrayList<>();
        if (mSohuDefinitionList != null && mSohuDefinitionList.size() > 0) {
            for (Integer i : mSohuDefinitionList) {
                stringArrayList.add(i + "");
            }
        }
        String currentDef = String.valueOf(((LVideoMediaPlayerControl) mPlayContorl).getCurrentDefinition());
        String videoCase = DefinitionManager
                .getVideoCaseByDefType(stringArrayList
                        , defType, currentDef);
        DefinitionManager.DefinitionObj definitionObj2
                = DefinitionManager.checkDefClassify(videoCase);
        if (TextUtils.isDigitsOnly(videoCase)) {
            try {
                int targetInt = Integer.valueOf(videoCase);
                ((LVideoMediaPlayerControl) mPlayContorl).changeDefinition(targetInt);
                mCurrPlayTime = getCurrPosition();
                reporterTime();
                bigDataPlayReporter.onStreamChange(vType);

                MyDataRecord record = MyDataRecordCreater.build(MyDataRecord.class);
                record.setAcode(SelfDataConstant.AC_PLAY);
                if(mPlayData != null && !TextUtils.isEmpty(mPlayData.getAid())){
                    record.setAid(mPlayData.getAid());
                }
                record.setPlayac(SelfDataConstant.PLAYAC_TG);
                record.setPt(mRealPlayTime +"");
                RealmDaoManager.addMyDataRecord(record);

                if (definitionObj2 != null) {
                    bottomTips = mSelfOwnActivity.getResources().getString(definitionObj2.showTextResId);
                }
                setSohuPlayerDefinition(targetInt);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        showVideoPrepareing();
    }

    private void changeOuterDefinition(String defType, String vType) {
        mCurrPlayTime = getCurrPosition();
        LogUtils.e(TAG, "!!!!!!!!!!!!!!!!!!!!!切至" + defType + " cur playPos is " + mCurrPlayTime);
        reporterTime();
        bigDataPlayReporter.onStreamChange(vType);

        MyDataRecord record = MyDataRecordCreater.build(MyDataRecord.class);
        record.setAcode(SelfDataConstant.AC_PLAY);
        if(mPlayData != null && !TextUtils.isEmpty(mPlayData.getAid())){
            record.setAid(mPlayData.getAid());
        }
        record.setPlayac(SelfDataConstant.PLAYAC_TG);
        record.setPt(mRealPlayTime +"");
        RealmDaoManager.addMyDataRecord(record);

        String videoCase = DefinitionManager
                .getVideoCaseByDefType(videoCaseList
                        , defType, mOutsiteClarity);
        mOutsiteClarity = videoCase;
        DefinitionManager.DefinitionObj definitionObj2
                = DefinitionManager.checkDefClassify(videoCase);
        if (definitionObj2 != null) {
            mClarity_select.setText(definitionObj2.showTextResId);
            bottomTips = mSelfOwnActivity.getResources().getString(definitionObj2.showTextResId);
        }
        executeClarityChangePlay();
    }

    public void selectUiChange() {
        // 如果选集面板已经展现则隐藏
        if (mSelectLinearLayout.isShown()) {
            setSelectLayoutVisibile(false);
            setLockScreenVisibile(true);
            setMediaControllerBottomVisibile(true);
        } else {
            setMediaControllerBottomVisibile(false);
            setLockScreenVisibile(false);
            setSelectLayoutVisibile(true);
        }
    }

    private void setFloorControllerGone() {
        setMediaControllerTopVisibile(false);
        setMediaControllerBottomVisibile(false);
        setLockScreenVisibile(false);
        if (null != mSelfOwnActivity) {
            if (mIsFullScreen) {
                statusBarShow(false);
            }
            if (Utils.getAPILevel() >= PlayerUtils.API_14) {
                PlayerUtils.hideVirtualKey(mWindow);
            }
        }
    }

    /**
     * 需要暂停 返回true
     * 无需暂停 返回false
     * @return
     */
    public boolean mobileNetNeedPause() {
        if (mPlayContorl != null && mPlayContorl.isPlaying()) {
            onPause();
            mVideoViewPosition.setVisibility(View.GONE);
            setPlayLoadingVisibile(false);
            attachAdLinearLayout.setVisibility(View.GONE);
            attachAdBottomLinearLayout.setVisibility(View.GONE);
            return true;
        }
        if (!mIsPause && mVideoViewPosition != null && mVideoViewPosition.getVisibility() == View.VISIBLE) {
            mVideoViewPosition.setVisibility(View.GONE);
            setPlayLoadingVisibile(false);
            attachAdLinearLayout.setVisibility(View.GONE);
            attachAdBottomLinearLayout.setVisibility(View.GONE);
            return true;
        }
        return false;
    }

    public boolean isMobileNetWork() {
        ConnectivityManager manager = (ConnectivityManager) mSelfOwnActivity
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (null == manager) {
            return false;
        }
        NetworkInfo wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo gprs = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (null == wifi || null == gprs) {
            return false;
        }
        if (gprs.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }

    public void clickPauseOrPlay() {
        if (null != mPlayContorl) {
            if (mPlayContorl.isPlaying() && mPlayContorl.canPause()) {
                mIsPause = true;
                reporterTime();
                bigDataPlayReporter.onPlayPause();
                pauseTimeCircleReport();

                playerPause();
                stopPlayerTimer();
                mCurrPlayTime = mPlayContorl.getCurrentPosition();

            } else {
                mIsPause = false;
                if (!PlayerUtils.SITE_CLOUDDISK.equals(mPlayData.getSite())) {
                    isCloud = false;
                } else {
                    isCloud = true;
                }
                mTimeMillis = System.currentTimeMillis();
                bigDataPlayReporter.onPlayResume();

                MyDataRecord record = MyDataRecordCreater.build(MyDataRecord.class);
                record.setAcode(SelfDataConstant.AC_PLAY);
                if(mPlayData != null && !TextUtils.isEmpty(mPlayData.getAid())){
                    record.setAid(mPlayData.getAid());
                }
                record.setPlayac(SelfDataConstant.PLAYAC_RESUME);
                record.setPt(mRealPlayTime +"");
                RealmDaoManager.addMyDataRecord(record);

                if (mSelfOwnActivity instanceof VideoDetailActivity) {
                    if (((VideoDetailActivity) mSelfOwnActivity).fromBackground) {
                        mPlayContorl.seekTo(mCurrPlayTime);
                        ((VideoDetailActivity) mSelfOwnActivity).fromBackground = false;
                    }
                    if (((VideoDetailActivity) mSelfOwnActivity).updatePlayPageInWorkMobile()) {
                        mPlayContorl.start();
                        updatePlayBtnBg(mIsPause);
                        onPause();
                        mVideoViewPosition.setVisibility(View.GONE);
                        ((VideoDetailActivity) mSelfOwnActivity).refreshToMobileNet();
                        ((VideoDetailActivity) mSelfOwnActivity).setPlayingProcess(true);
                        return;
                    }
                } else if (mSelfOwnActivity instanceof PlayActivitySelfOwn) {
                    if (((PlayActivitySelfOwn) mSelfOwnActivity).fromBackground) {
                        mPlayContorl.seekTo(mCurrPlayTime);
                        ((PlayActivitySelfOwn) mSelfOwnActivity).fromBackground = false;
                    }
                }
                mPlayContorl.start();
                mTimeMillis = System.currentTimeMillis();
                startPlayerTimer();
            }
        } else {
            if (mIsPause) {
                executeProcessBySite(mPlayData.getSite());
            }
        }
        updatePlayBtnBg(mIsPause);
    }

    /**
     * 更新播放按钮背景
     *
     * @param isPauseState zhangshuo 2014年4月29日 上午10:05:38
     */
    private void updatePlayBtnBg(boolean isPauseState) {
        if (null != mPlayBtn) {
            if (isPauseState) {
                // 暂停状态设置为播放按钮
                mPlayBtn.setBackgroundResource(R.drawable.videoplayer_play_selector);
                mCenterPlayIv.setVisibility(View.VISIBLE);
                mPauseAd = null;
                requestPauseAd();
                if(!mIsPlayLocalUrl){
                    if(mIsFullScreen){
                        UmengEventPoster.postPlayerPause("fullscreen");
                    }else{
                        UmengEventPoster.postPlayerPause("detail");
                    }
                }
            } else {
                mPlayBtn.setBackgroundResource(R.drawable.videoplayer_pause_selector);
                mCenterPlayIv.setVisibility(View.GONE);
                mIsPause = false;
                showPauseAd();
            }
        }
    }

    private OnSeekBarChangeListener mPlaySeekBarChangeListener = new OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mHandler.sendEmptyMessageDelayed(Utils.DISSMISS_MEDIACONTROLLER,
                    Utils.MEDIA_CONTROLLER_DISMISS_TIME);

            // 影藏当前拖动的显示的时间
            if (null != mDragCurrTime && mDragCurrTime.isShown()) {
                mDragCurrTime.setVisibility(View.INVISIBLE);
            }
            setDataPauseTs(getCurrPosition());

            int seekBarProgress = seekBar.getProgress();
            long position = 0;
            if (mDuration > 0 && null != mPlayContorl && null != mCurrTime) {
                position = (mDuration * seekBarProgress / PLAY_SEEKBAR_MAX);
                mPosition = position;

                int streamIndex = getStreamPosition(position);
                setDataPlayTs(position);

                if (streamIndex != mStreamIndex && mStream_list != null &&
                        mStream_list.size() > 1) {
                    mStreamIndex = streamIndex;
                    mIsStartNewPlayerByDrag = true;
                    if (!mIsPlayLocalUrl) {
                        doPlay(PlayerUtils.DEFAULT_PLAYER_TYPE, mStream_list.get(streamIndex));
                    } else {
                        doPlayLocalVideo(mStream_list.get(streamIndex));
                    }
                } else {
                    mIsStartNewPlayerByDrag = false;
                    mPlayContorl.seekTo((int) position);
                }
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            stopPlayerTimer();
            mHandler.removeMessages(Utils.DISSMISS_MEDIACONTROLLER);
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            bigDataPlayReporter.setDuration(mDuration);
            bigDataPlayReporter.onProgress(progress, PLAY_SEEKBAR_MAX);
            if (!fromUser) {
                return;
            }
            long duration = mDuration;

            int mUserDragTime = (int) ((duration * seekBar.getProgress()) / PLAY_SEEKBAR_MAX);
            String dragTime = PlayerUtils.toStringTime(mUserDragTime);
            mCurrTime.setText(dragTime);

            if (null != mDragCurrTime) {
                mDragCurrTime.setText(dragTime);
                updateDragSeekBarPosition(progress);
            }
        }

    };

    private int getStreamPosition(long position) {
        if (mStreamListTime == null || mStreamListTime.size() <= 0 ||
                mStream_list == null) {
            return 0;
        }
        int streamPosition = 0;
        for (int i = 0; i < mStream_list.size(); i++) {
            if (position > mStreamListTime.get(i).intValue()) {
                position -= mStreamListTime.get(i).intValue();
            } else {
                streamPosition = i;
                break;
            }
        }
        return streamPosition;
    }

    private long getLastStream(long position) {
        if (mStreamListTime == null || mStreamListTime.size() <= 0
                || mStream_list == null) {
            return -1;
        }
        long lastStream = 0;
        for (int i = 0; i < mStream_list.size(); i++) {
            if (position > mStreamListTime.get(i).intValue()) {
                position -= mStreamListTime.get(i).intValue();
            } else {
                lastStream = position;
                break;
            }
        }
        return lastStream;
    }

    private void updateDragSeekBarPosition(int progress) {
        if (null != mDragCurrTime) {
            if (!mDragCurrTime.isShown()) {
                mDragCurrTime.setVisibility(View.VISIBLE);
            }
            RelativeLayout.LayoutParams lp = (LayoutParams) mDragCurrTime
                    .getLayoutParams();
            int leftMargin = mPlaySeekBar.getLeft()
                    + getSeekbarThumpPosintion(progress)
                    - mPlaySeekBar.getThumbOffset() + UIs.dipToPx(8);
            lp.leftMargin = leftMargin;
            mDragCurrTime.setLayoutParams(lp);
        }
    }

    private int getSeekbarThumpPosintion(int progress) {
        double offsetX = 0;
        if (null != mPlaySeekBar) {
            int seekbarWidth = mPlaySeekBar.getWidth()
                    - mPlaySeekBar.getPaddingLeft()
                    - mPlaySeekBar.getPaddingRight()
                    - mPlaySeekBar.getThumbOffset();
            offsetX = (new Double(progress) / mPlaySeekBar.getMax())
                    * seekbarWidth;
        }
        return (int) offsetX;
    }

    private OnSeekCompleteListener mPlaySeekCompleteListener = new OnSeekCompleteListener() {
        @Override
        public void onSeekComplete(MediaPlayer mp) {
            // 当前拖动完成并且不是暂停状态时开始播放并刷新UI页面
            if (null != mPlayContorl && !mIsPause) {
                if(isFirstDragReported){
                    bigDataPlayReporter.onPlayDrag();
                    reporterTime();
                }else{
                    isFirstDragReported = true;
                }
                if(!(mPlayContorl instanceof VideoViewPPTVProxy || mPlayContorl instanceof VideoViewLetvProxy)){
                    mPlayContorl.start();
                }
                startPlayerTimer();
            } else if (mIsPause) {
                mPlayContorl.pause();
            }
        }
    };

    /**
     * 第一次上报
     */
    private void startPlayTimeReport() {
        play_start = System.currentTimeMillis();
        mTimeMillis = System.currentTimeMillis();
        stopTimeCircleReport();
        circleReport();
    }

    /**
     *
     */
    private void circleReport() {
        if (!mHandler.hasMessages(Utils.TIME_REPORT)) {
            mHandler.sendEmptyMessageDelayed(Utils.TIME_REPORT, getNextStepTime());
        }
    }

    /**
     * 停止time上报
     */
    public void stopTimeCircleReport() {
        try {
            if (mThirdReportTimer != null) {
                mThirdReportTimer.cancel();
                mThirdReportTimer = null;
            }
            if (null != mHandler && mHandler.hasMessages(Utils.TIME_REPORT)) {
                mHandler.removeMessages(Utils.TIME_REPORT);
                mCurrentStep = 0;   //这里重置为第一次开始上报
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 中断time上报
     */
    public void pauseTimeCircleReport() {
        try {
            if (mThirdReportTimer != null) {
                mThirdReportTimer.cancel();
                mThirdReportTimer = null;
            }
            if (null != mHandler && mHandler.hasMessages(Utils.TIME_REPORT)) {
                mHandler.removeMessages(Utils.TIME_REPORT);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 开启计时器，秒刷新界面
     */
    protected void startPlayerTimer() {
        // 当前不是暂停状态并且播放器已经准备好了才开始刷新页面
        try {
            if (!mIsPause) {
                stopPlayerTimer();
                if (mPlayerTimer == null) {
                    mPlayerTimer = new PlayerTimer(mHandler, Utils.PROGRESS_CHANGE);
                    Timer m_musictask = new Timer();
                    m_musictask.schedule(mPlayerTimer, 0, 1000);
                }
                circleReport();
            }
        } catch (Error e) {
            //Maybe could not allocate JNI Env
            LogUtils.e(e.getMessage());
        }
    }

    /**
     * 停止播放器计时
     */
    protected void stopPlayerTimer() {
        try {
            if (mPlayerTimer != null) {
                mPlayerTimer.cancel();
                mPlayerTimer = null;
            }
            if (null != mHandler && mHandler.hasMessages(Utils.JUDGE_BUFFER)) {
                mHandler.removeMessages(Utils.JUDGE_BUFFER);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void playerPause() {
        if (null != mPlayContorl && mIsPrepared) {
            mCurrPlayTime = getCurrPosition();
            savePlayRecord(mCurrPlayTime);
        }
        if (null != mPlayContorl) {
            mPlayContorl.pause();
        }
    }

    public void startPlayer() {
        if (null != mPlayContorl && mIsPrepared && !mIsPause) {
            if (mPlayContorl instanceof VideoViewPPTVProxy || mPlayContorl instanceof VideoViewLetvProxy) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mPlayContorl != null && mPlayContorl instanceof VideoViewPPTVProxy) {
                            mSohuDefinitionList = ((LVideoMediaPlayerControl) mPlayContorl).getSupportDefinitions();
                            mClaritymap = DefinitionManager.getSupportDefMapOnlyOuter((ArrayList<Integer>)mSohuDefinitionList);
                            setSohuPlayerDefinition(((LVideoMediaPlayerControl) mPlayContorl).getCurrentDefinition());
                        }
                    }
                }, 5000);
            } else {
                mPlayContorl.start();
            }
            if (mIsStartNewPlayerByDrag) {
                mPlayContorl.seekTo((int) getLastStream(mPosition));
                if (mPlayPeriod != null) {
                    mPlayPeriod.setRePlayTs((int) getLastStream(mPosition));
                }
                mIsStartNewPlayerByDrag = false;
            }
            mIsPause = false;
        }
    }

    /**
     * 设置顶部标题名称
     *
     * @param text zhangshuo 2014年5月2日 下午10:42:40
     */
    private void setTitleText(String text) {
        if (null != mTitile && !TextUtils.isEmpty(text)) {
            mTitile.setVisibility(View.VISIBLE);
            if (mIsPlayLocalUrl) {
                mTitile.setText(text);
                mTitleWebsite.setText("本地");
            } else {
                if (StringUtil.isEmpty(mPlayData.getSitNmae())) {
                    mTitile.setText(text);
                    mTitleWebsite.setText(mPlayEpisode.getPlay_url());
                } else {
                    mTitile.setText(text);
                    mTitleWebsite.setText(mPlayData.getSitNmae() + ":" + mPlayEpisode.getPlay_url());
                }

                if(PlayerUtils.SITE_CLOUDDISK.equals(mPlayData.getSite()) && !TextUtils.isEmpty(mPlayEpisode.getPlay_url())){
                    mTitleWebsite.setText(mPlayEpisode.getPlay_url());
                }
            }
        } else if (null != mTitile && TextUtils.isEmpty(text)) {
            mTitile.setVisibility(View.GONE);
        }
    }

    /**
     * 获取当前的播放位置 zhangshuo 2014年5月4日 上午11:02:57
     */
    private int getCurrPosition() {
        if (null != mPlayContorl) {
            return mPlayContorl.getCurrentPosition();
        }
        return 0;
    }

    private int getDuation() {
        if (null != mPlayContorl) {
            return mPlayContorl.getDuration();
        }
        return 0;
    }

    /**
     * 切换播放器
     *
     * @param currPlayType zhangshuo 2014年5月4日 上午11:41:43
     */
    private boolean changePlayer(int currPlayType) {
        try {
            if (null != mVideoViewPosition) {
                // 释放播放资源
                resetPlayerData();
                PlayerUtils.DEFAULT_PLAYER_TYPE = currPlayType;
                if (null != mPlayerView) {
                    // 移除播放器
                    mPlayerView.setVisibility(View.GONE);
                    mVideoViewPosition.removeView(mPlayerView);
                }
                if (null != mPlayPasterAdView) {
                    mVideoViewPosition.removeView(mPlayPasterAdView);
                }
                mPlayContorl = mVideoViewBuilder.build(mSelfOwnActivity,
                        PlayerUtils.DEFAULT_PLAYER_TYPE);
                mPlayerView = mPlayContorl.getView();
                RelativeLayout.LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
                params.addRule(RelativeLayout.CENTER_IN_PARENT);
                mVideoViewPosition.addView(mPlayerView, params);
                // 设置播放器监听事件
                setPlayerListener();
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 展现控制栏 zhangshuo 2014年5月4日 下午8:41:41
     */
    private void showMediaControll(Boolean isFullScreen) {
        if (null != mSelfOwnActivity) {
            if (isFullScreen) {
                statusBarShow(false);
            }
            if (isFullScreen && Utils.getAPILevel() >= PlayerUtils.API_14) {
                PlayerUtils.showVirtualKey(mWindow);
            }
        }
        if (null != mMediaControllerTop && null != mMediaControllerBottmon) {
            mIsControllerShow = true;
            if (!mMediaControllerTop.isShown()) {
                mMediaControllerTop.setVisibility(View.VISIBLE);
            }

            if (!mMediaControllerBottmon.isShown()) {
                mMediaControllerBottmon.setVisibility(View.VISIBLE);
            }
        }
        if (null != bottomTipsTv && !TextUtils.isEmpty(bottomTips) && null != mSelfOwnActivity) {
            String strItem = String.format(MoviesUtils.isProductCjsp()?"%s<font color=#F44343>%s</font>":
                            "%s<font color=#3599f8>%s</font>",
                    mSelfOwnActivity.getResources().getString(R.string.bottom_tips_txt) + " ", // 字符串1
                    bottomTips);

            bottomTipsTv.setText(Html.fromHtml(strItem));
            if (mMediaControllerBottmon != null && mMediaControllerBottmon.getVisibility() == View.VISIBLE) {
                bottomTipsTv.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 隐藏控制栏 zhangshuo 2014年5月4日 下午8:42:00
     */
    private void dissMissMediaControll(boolean isFullScrreen) {
        if (null != mSelfOwnActivity) {
            if (isFullScrreen) {
                statusBarShow(false);
            }
            // 隐藏虚拟键操作
            if (isFullScrreen && Utils.getAPILevel() >= PlayerUtils.API_14) {
                PlayerUtils.hideVirtualKey(mWindow);
            }
        }

        if (null != mMediaControllerTop && null != mMediaControllerBottmon) {
            mIsControllerShow = false;
            mMediaControllerTop.setVisibility(View.GONE);
            setChangeClarityVisibile(false);
            mMediaControllerBottmon.setVisibility(View.GONE);
        }

        if (bottomTipsTv != null) {
            bottomTipsTv.setVisibility(View.GONE);
            bottomTips = "";
        }

        setSelectLayoutVisibile(false);
    }

    /**
     * 动态展现控制栏 zhangshuo 2014年5月5日 上午9:53:19
     */
    private void dynamicShowControll(boolean isFullScreen) {
        if (mIsControllerShow) {
            dissMissMediaControll(isFullScreen);
            setLockScreenVisibile(false);
        } else {
            setLockScreenVisibile(true);
            showMediaControll(isFullScreen);
        }
        mHandler.removeMessages(Utils.DISSMISS_MEDIACONTROLLER);
        mHandler.sendEmptyMessageDelayed(Utils.DISSMISS_MEDIACONTROLLER,
                Utils.MEDIA_CONTROLLER_DISMISS_TIME);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (!mIsPrepared) {
            return false;
        }
        switch (v.getId()) {
            case R.id.full_play_seekbar:
                if (mIsLoadAllPiece) {
                    return false;
                }
                return true;
            case R.id.mediacontroller_top:
            case R.id.layout_mediacontroller_bottom:
                return true;
            case R.id.videoview_position:
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    count++;
                    if (count == 1) {
                        firClick = System.currentTimeMillis();
                    } else if (count == 2) {
                        secClick = System.currentTimeMillis();
                        if (secClick - firClick < 200 && !mLockScreenBtn.isSelected()) {
                            clickPauseOrPlay();
                            mHandler.sendEmptyMessageDelayed(Utils.DISSMISS_MEDIACONTROLLER,
                                    Utils.MEDIA_CONTROLLER_DISMISS_TIME);
                            mHandler.removeMessages(Utils.TOP_CONTROL);
                            count = 0;
                            firClick = 0;
                            secClick = 0;
                            return true;
                        }

                    }
                    mHandler.sendEmptyMessageDelayed(Utils.TOP_CONTROL, 200);
                }
                if (null != mGestureHandle && !mLockScreenBtn.isSelected()) {
                    mGestureHandle.handleGestureSlide(event, mPlayContorl);
                }
                return true;
            default:
                break;
        }
        return false;
    }

    private void initAudioVolume() {
        mAudioManager = (AudioManager) mSelfOwnActivity
                .getSystemService(Context.AUDIO_SERVICE);
        VOLUME_MAX = mAudioManager
                .getStreamMaxVolume(AudioManager.STREAM_MUSIC) * 100;
        int streamVolume = mAudioManager
                .getStreamVolume(AudioManager.STREAM_MUSIC) * 100;
        mIsSilent = (streamVolume == VOLUME_MIN);
        if (!mIsSilent || mCurrentVolume == VOLUME_UNINIT) {
            mCurrentVolume = streamVolume;
        }
    }

    /**
     * 设置当前的音量
     */
    public void setCurrentVolume(int volume) {
        if (volume > VOLUME_MAX) {
            volume = VOLUME_MAX;
        } else if (volume < VOLUME_MIN) {
            volume = VOLUME_MIN;
        }
        mCurrentVolume = volume;
        mIsSilent = (mCurrentVolume == VOLUME_MIN);

        updateCurrentVolumeDisplay();
    }

    /**
     * 更新系统音量以及音量进度条
     */
    private void updateCurrentVolumeDisplay() {
        if (mAudioManager == null) {
            return;
        }
        int targetVolume = mIsSilent ? 0 : mCurrentVolume;

        // mFullScreenVolumSeekBar.setProgress(targetVolume);
        if (mSystemHardKeyAdjustVolume) {
            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                    (int) (targetVolume / 100), AudioManager.FLAG_PLAY_SOUND
                            | AudioManager.FLAG_SHOW_UI);
            mSystemHardKeyAdjustVolume = false;
        } else {
            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                    (int) (targetVolume / 100), 0);
        }

        // mVolumControlBtn.setSelected(mIsSilent);
    }

    public void showControllerLogic() {
        if (mLockScreenBtn.isSelected()) {
            if (mLockScreenBtn.isShown()) {
                mLockScreenBtn.startAnimation(mLockScreenAni);
            } else {
                setLockScreenVisibile(true);
            }
            mHandler.removeMessages(Utils.DISSMISS_MEDIACONTROLLER);
            mHandler.sendEmptyMessageDelayed(Utils.DISSMISS_MEDIACONTROLLER,
                    Utils.MEDIA_CONTROLLER_DISMISS_TIME);
        } else {
            dynamicShowControll(mIsFullScreen);
        }
    }

    public UMengReport getmUMengReport() {
        return mUMengReport;
    }

    public void onPause() {
        // 如果当前正在播放则停止计时并暂停播放
        if(attachAdLinearLayout != null && attachAdBottomLinearLayout != null){
            attachAdLinearLayout.setVisibility(View.GONE);
            attachAdBottomLinearLayout.setVisibility(View.GONE);
            setSound(false);
        }
        if (null != mPlayContorl && mIsPlayingAdvertisement) {
            mPlayAdPisition = mPlayContorl.getCurrentPosition();
            LogUtils.e("AD", "play ad position is " + mPlayAdPisition);
            if (mPlayContorl instanceof VideoViewBestvProxy) {
                ((VideoViewBestvProxy) mPlayContorl).onAdPause();
                ((VideoViewBestvProxy) mPlayContorl).onActivityPause();
            } else {
                mPlayContorl.pause();
            }
            mHandler.removeMessages(Utils.AD_SECOND);
            if (mPlayContorl instanceof VideoViewPasterProxy) {
                attachAdLinearLayout.setVisibility(View.VISIBLE);
                attachAdBottomLinearLayout.setVisibility(View.VISIBLE);
            }
        }
        if (null != mPlayContorl && mPlayContorl.isPlaying() && !(mPlayContorl instanceof VideoViewPasterProxy)) {

            reporterTime();
            bigDataPlayReporter.setAc(BigDataConstants.PLAY_AC_BACKGROUND);
            bigDataPlayReporter.onPlayProcess();
            mCurrPlayTime = getCurrPosition();
            stopPlayerTimer();
            if (!(mPlayContorl instanceof VideoViewBestvProxy)) {
                playerPause();
            }
            if (!mIsPlayLocalUrl) {
                // 重置云盘播放位置
                mCloudPlayPosition = 0;

                if (null != mPlayContorl) {
                    if (mPlayContorl instanceof VideoViewBestvProxy) {
                        ((VideoViewBestvProxy) mPlayContorl).onActivityPause();
                    } else {
                        mPlayContorl.stopPlayback();
                        mPlayContorl = null;
                    }
                }

                stopCdeSource();
//                setControllerUI();
            }
        }
        if (mPlayContorl instanceof VideoViewFunshionProxy) {
            ((VideoViewFunshionProxy)mPlayContorl).onActivityPause();
        }
    }

    public void onDestroy() {
        if (mPlayContorl instanceof VideoViewFunshionProxy) {
            ((VideoViewFunshionProxy)mPlayContorl).onActivityDestroy();
        }
        mLetvView = null;
        mNetClarityListener = null;
        if (null != mPlayContorl) {
            mPlayContorl.stopPlayback();
            if (mPlayContorl instanceof LVideoMediaPlayerControl) {
                ((LVideoMediaPlayerControl) mPlayContorl).onDestroyData();
            }
            mPlayContorl = null;
        }
        mSelfOwnActivity = null;
        if (mGestureHandle != null) {
            mGestureHandle.destroyResource();
            mGestureHandle = null;
        }
        if (mRequstCloudErrorTask != null) {
            mRequstCloudErrorTask.cancel();
            mRequstCloudErrorTask.setListener(null);
            mRequstCloudErrorTask = null;
        }
        if (mRequestAdTask != null) {
            mRequestAdTask.cancel();
            mRequestAdTask.setListener(null);
            mRequestAdTask = null;
        }
    }

    private void stopCdeSource() {
        LogUtils.e(TAG, "@@@@@@@@@@mLinkShellUrl@@@@@@@@" + mLinkShellUrl);
        if (!TextUtils.isEmpty(mLinkShellUrl)) {
            CdeHelper cdeHelper = mCDEManager.getmCdeHelper();
            cdeHelper.stopPlay(mLinkShellUrl);
            LogUtils.e(TAG, "***********mLinkShellUrl**********"
                    + mLinkShellUrl);
        }
    }

    public void onResume() {
        if (mPlayerStatus != null && mPlayerStatus.getVisibility() != View.VISIBLE && mVideoViewPosition != null && mVideoViewPosition.getVisibility() != View.VISIBLE) {
            mVideoViewPosition.setVisibility(View.VISIBLE);
        }
        if ((mIsPrepared && !mIsPause) || mIsPlayingAdvertisement) {
            bigDataPlayReporter.onUuidChange(); // 从后台切回前台更新uuid
            if (mIsPlayLocalUrl) {
                startPlayerTimer();
                mPlayContorl.seekTo(mCurrPlayTime);
                mPlayContorl.start();
            } else if (mPlayContorl instanceof VideoViewPasterProxy) {
                if (((VideoViewPasterProxy)mPlayContorl).isPlayingPhoto()) {
                    adSecond = (mPlayContorl).getCurrentPosition();
                    String sec = " " + adSecond;
                    attachAdSecond.setText(sec);
                } else {
                    mPlayContorl.start();
                    mPlayContorl.seekTo(mPlayAdPisition);
                    adSecond = Integer.valueOf(((HzPayload) mPasterAd.payload).ad.duration) - mPlayAdPisition / 1000;
                    String sec = " " + adSecond;
                    attachAdSecond.setText(sec);
                }
                mHandler.removeMessages(Utils.AD_SECOND);
                mHandler.sendEmptyMessageDelayed(Utils.AD_SECOND, 1000);
                attachAdLinearLayout.setVisibility(View.VISIBLE);
                attachAdBottomLinearLayout.setVisibility(View.VISIBLE);
            } else if (mPlayContorl instanceof VideoViewBestvProxy) {
                ((VideoViewBestvProxy) mPlayContorl).onActivityResume();
            } else {
                // 如果当前播放的是在线视频则从新获取播放地址并播放,这样做是为了放是播放地址过期
                bigDataPlayReporter.onPlayerInit(); // 播放器初始化上报
                isBigDataInit = true;
                executeProcessBySite(mPlayEpisode.getSite());
                selfReportPlayInit();
            }
        }
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        }
        if (mPlayContorl instanceof VideoViewFunshionProxy) {
            ((VideoViewFunshionProxy)mPlayContorl).onActivityResume();
        }
    }

    public boolean ismIsPrepared() {
        return mIsPrepared;
    }

    public Activity getmSelfOwnActivity() {
        return mSelfOwnActivity;
    }

    private void savePlayRecord(long currentPosition) {
        if (mIsPlayLocalUrl) {
            LocalVideoEpisode localVideoEpisode = mLocalPlayLists
                    .get(mVideoPosition);
            saveLocalToPlayRecord(mLocalPlayLists.get(mVideoPosition),
                    currentPosition);
            updateLocalPlaySatate(localVideoEpisode);
        } else {
            saveToPlayRecord(mPlayEpisode, currentPosition);
        }
    }

    /**
     * 更新缓存页面的红点 zhangshuo 2014年7月9日 上午11:32:50
     */
    private void updateLocalPlaySatate(LocalVideoEpisode localVideoEpisode) {
        String id = localVideoEpisode.getId();
        if (!TextUtils.isEmpty(id)) {
            DownloadManager downLoadManager = MoviesApplication.getInstance()
                    .getDownloadManager();
            DownloadEntity dowloadEntity = new DownloadEntity();
            dowloadEntity.setId(id);
            downLoadManager.setIfWatch(dowloadEntity, "true");
        }
    }

    private void saveLocalToPlayRecord(LocalVideoEpisode localVideoEpisode,
                                       long currentPosition) {
        mPlayData.getmPlayRecord().setAid(localVideoEpisode.getAid());
        mPlayData.getmPlayRecord().setPorder(localVideoEpisode.getPorder());
        mPlayData.getmPlayRecord().setUrl(localVideoEpisode.getPlay_url().get(0));
        mPlayData.getmPlayRecord().setSeekHistory(currentPosition);
        mPlayData.getmPlayRecord().setName(localVideoEpisode.getName());
        DownLoadPlayRecordDao.getInstance(mSelfOwnActivity).save(
                mPlayData.getmPlayRecord());
    }

    /**
     * 保存播放记录
     */
    private void saveToPlayRecord(Episode ep, long currentPosition) {
        if (ep != null && mPlayData != null && null != mPlayData.getmPlayRecord()) {
            mPlayData.getmPlayRecord().setPageIndex(ep.getPageIndex());
            mPlayData.getmPlayRecord().setCurrentPagePosition(ep.getCurrentPagePosition());
            mPlayData.getmPlayRecord().setPorder(ep.getPorder());
            mPlayData.getmPlayRecord().setUrl(ep.getPlay_url());
            mPlayData.getmPlayRecord().setEpisodeName(ep.getPorder());
            mPlayData.getmPlayRecord().setSeekHistory(currentPosition);
            mPlayData.getmPlayRecord().setVid(ep.getGlobaVid());
            mPlayData.getmPlayRecord().setTime(System.currentTimeMillis());
            mPlayData.getmPlayRecord().setPoster(mPlayData.getPoster());
            mPlayData.getmPlayRecord().setSite(TextUtils.isEmpty(ep.getSite()) ? mPlayData.getSite() : ep.getSite());
//            mPlayData.getmPlayRecord().setCategory();
            if (mLoginSP != null && !TextUtils.isEmpty(mLoginSP.getString(LoginActivity.TOKEN, ""))) {
                List<PlayRecord> list = new ArrayList<PlayRecord>();
                list.add(mPlayData.getmPlayRecord());
                new RequestDoPlayRecordTask(mSelfOwnActivity, list, "add").start();
            } else {
                mPlayRecordDao.save(mPlayData.getmPlayRecord());
            }
        }
    }

    public void setPlayErrorLayoutVisibile(boolean flag) {
        if (null != mPlayErrorLayout) {
            if (flag) {
                mPlayErrorLayout.setVisibility(View.VISIBLE);
            } else {
                mPlayErrorLayout.setVisibility(View.GONE);
            }
        }
    }

    private void bufferStart(final int position) {
        showVideoLoading();
        setPlayLoadingVisibile(true);
        if (!ismIsPause()) {
            //延时3秒判断卡顿
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (getCurrPosition() == position) {
                        mPlayBuffer = mPlayDataReport.new PlayBuffer();
                        mPlayBuffer.setAbBufferStartTs(System.currentTimeMillis());
                    }
                }
            }, 3000);
        }
    }

    private void bufferEnd() {
        setPlayLoadingVisibile(false);
        if (mPlayBuffer != null) {
            mPlayBuffer.setAbBufferEndTs(System.currentTimeMillis());
            mPlayBuffer.setReBufferTs(mCurrPlayTime);
            mPlayDataReport.addPlayBuffer(mPlayBuffer);
            mPlayBuffer = null;
        }
        startPlayer();
    }

    public boolean ismIsPause() {
        return mIsPause;
    }

    public void setmIsPause(boolean mIsPause) {
        this.mIsPause = mIsPause;
    }

    private void setLockScreenVisibile(boolean flag) {
        if (null != mLockScreenBtn) {
            if (flag) {
                mLockScreenBtn.setVisibility(View.VISIBLE);
            } else {
                mLockScreenBtn.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 创建锁屏动画
     *
     * @param context
     * @return zhangshuo 2014年7月4日 下午4:47:18
     */
    private Animation makeBlinkAnimation(Context context) {
        Animation blinkAnimation = AnimationUtils.loadAnimation(context,
                R.anim.blink_alpha);
        blinkAnimation.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
                mHandler.removeMessages(Utils.DISSMISS_MEDIACONTROLLER);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mHandler.sendEmptyMessageDelayed(
                        Utils.DISSMISS_MEDIACONTROLLER,
                        Utils.MEDIA_CONTROLLER_DISMISS_TIME);
            }
        });
        return blinkAnimation;
    }

    public ImageButton getmLockScreenBtn() {
        return mLockScreenBtn;
    }

    private void setSelectVisibile(boolean flag) {
        if (null != mSelectBtn) {
            if (flag) {
                mSelectBtn.setVisibility(View.VISIBLE);
            } else {
                mSelectBtn.setVisibility(View.GONE);
                isNeedShowSelect = false;
            }
        }
    }

    private void setNextBtnVisibile(boolean flag) {
        if (null != mPlayNextBtn) {
            if (flag) {
                mPlayNextBtn.setVisibility(View.VISIBLE);
            } else {
                mPlayNextBtn.setVisibility(View.GONE);
                isNeedShowNext = false;
            }
        }
    }

    private void setSelectClickable(boolean flag) {
        if (null != mSelectBtn) {
            mSelectBtn.setClickable(flag);
        }
    }

    private void setSelectLayoutVisibile(boolean flag) {
        if (null != mSelectLinearLayout) {
            if (flag) {
                mSelectLinearLayout.setVisibility(View.VISIBLE);
            } else {
                mSelectLinearLayout.setVisibility(View.GONE);
            }
        }
    }

    public class SelectPeriodsItemClickListener implements EpisodeLocalPlayAdapter.OnItemClickListener {
        @Override
        public void onItemClick(View view, int position) {
            if (isEpisodeGridview(mLocalPlayLists.get(0).getVt())) {
                PlayEpisode(position, true);
            } else {
                PlayEpisode(position, false);
            }
        }
    }

    public void PlayEpisode(int position, boolean isGridAdapter) {
        int size = 0;
        if (position == mVideoPosition) {
            return;
        }
        if (null != mOutSiteStreamInfoTask && !mOutSiteStreamInfoTask.isCancelled()) {
            mOutSiteStreamInfoTask.cancel();
        }
        if (mSelfOwnActivity != null && mSelfOwnActivity instanceof VideoDetailActivity) {
            ((VideoDetailActivity) mSelfOwnActivity).onRefreshPlayerListener(position);
        }
        setDataPauseTs(mCurrPlayTime);
        String uploadPlayData = mPlayDataReport.toString();
        new ReportPlaySessionTask(MoviesApplication.getInstance(), uploadPlayData).start();
        if(mIsPrepared){
            selfReportPlayEnd();
        }
        if (isBigDataInit) {
            bigDataPlayReporter.onPlayEnd();// 手动切换剧集上报end动作
            isBigDataInit = false;
        }
        // 设置当前的播放位置
        mVideoPosition = position;
        // 首先判断是在线还是本地的Adapter
        setSelectLayoutVisibile(false);
        setSelectClickable(true);
        executeChangePrepared();
        bigDataPlayReporter.resetUUID();
        isFirstDragReported = false;
        LogUtils.e("wym", "SelectPeriods select called and cur uuid " + bigDataPlayReporter.getUUID());
        if (!mIsPlayLocalUrl) {
            size = mPlayData.getmPorderLists().size();
            // 获取用户点击指定位置的Episode
            Episode episode = null;
            if(position < mEpisodes.size()){
                episode = mEpisodes.get(position);
            }
            if (episode != null) {
                mPlayDataReport = new PlayDataReporter();
                if (MoviesConstant.VT_ZONGYI.equals(mPlayData.getVt())) {
                    bottomTips = "第 " + episode.getPorder() + " 期";
                } else {
                    bottomTips = "第 " + episode.getPorder() + " 集";
                }
                if (PlayerUtils.SITE_CLOUDDISK.equals(mPlayData.getSite())) {
                    lvideoVideoCode = PlayerUtils.PLS_MP4_350;  //云盘切集之后重置清晰度
                }
                ischangeClarity = false;
                mIsAllowLetvSdk = true;
                executeCommonPlay(episode);
            }
        } else {
            if (null != mLocalPlayLists) {
                size = mLocalPlayLists.size();
            }
            LocalVideoEpisode localVideoEpisode = (LocalVideoEpisode) mLocalAdapter.getItemByPosition(position);
            if (MoviesConstant.VT_ZONGYI.equals(localVideoEpisode.getVt())) {
                bottomTips = "第 " + localVideoEpisode.getPorder() + " 期";
            } else {
                bottomTips = "第 " + localVideoEpisode.getPorder() + " 集";
            }
            executeLocalPlayLogic(localVideoEpisode);
        }
        // 设置上下集标签
        setNextState(size);
    }

    public LinearLayout getmSelectLinearLayout() {
        return mSelectLinearLayout;
    }

    public class CloudDiskRequestListener implements
            RequestStreamResultListener<CloudDiskBean> {

        @Override
        public boolean onRequestFailed() {
            LogUtils.e(TAG, "!!!!!!!!!!!!!!!!!!!!!request cloud play data failed and reason maybe is user click too much in one minute!!!!!!!!!!!!!!!!!!!!!");
//            reTryPlay();
            mPlayStatusReport.setEndRequestTime(System.currentTimeMillis());
            reportPlayState(MoviesConstant.GET_PLAYURL_FAIL_STATE, "", "");
            cloudDiskError();
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, CloudDiskBean result) {
            // 如果首请求云盘MP4类型播放地址为空时则进行二次请求 请求m3u8播放源
            mPlayStatusReport.setEndRequestTime(System.currentTimeMillis());
            if (null != result) {
                mClaritymap = DefinitionManager.getSupportDefMapOnlyCloud(result);
                //判断默认地址是否为空, 不为空直接播放, 为空时从支持的清晰度选最低的一个
                if (null != result.getmPlayUrls()
                        && result.getmPlayUrls().size() > 0) {
                    lvideoVideoCode = result.getCurrClarity();
                    DefinitionManager.DefinitionObj definitionObj = DefinitionManager.checkDefClassify(lvideoVideoCode);
                    if (definitionObj != null) {
                        mClarity_select.setText(definitionObj.showTextResId);
                    }
                    mCloudPlayUrls = result.getmPlayUrls();
                    videoCaseList = new ArrayList<>();
                    videoCaseList.clear();
                    videoCaseList.addAll(result.getSupportVideoListObj().keySet());
                    if(mPlayData != null){
                        mPlayData.getEpisodes().get(0).setPls(StringUtil.listToString(videoCaseList, ","));
                    }
                    if(mNetClarityListener != null){
                        mNetClarityListener.loadNetClarityComplete(videoCaseList);
                    }
                    handleCDECloudUrl();
                } else {
                    if (mClaritymap.get(DefinitionManager.DEFINITION_TYPE_FLUENCY)) {
                        changeCloudDefinition(DefinitionManager.DEFINITION_TYPE_FLUENCY, PlayerUtils.VT_MP4);
                    } else if (mClaritymap.get(DefinitionManager.DEFINITION_TYPE_NORMAL)) {
                        changeCloudDefinition(DefinitionManager.DEFINITION_TYPE_NORMAL, PlayerUtils.VT_MP4_350);
                    } else if (mClaritymap.get(DefinitionManager.DEFINITION_TYPE_HIGH)) {
                        changeCloudDefinition(DefinitionManager.DEFINITION_TYPE_HIGH, PlayerUtils.VT_MP4_720p_db);
                    } else if (mClaritymap.get(DefinitionManager.DEFINITION_TYPE_SUPER)) {
                        changeCloudDefinition(DefinitionManager.DEFINITION_TYPE_SUPER, PlayerUtils.VT_MP4_720P);
                    }
                }
            } else {
                // 如果当前请求云盘的播放格式是M3u8那么可以开始请求MP4播放源
                if (mCurrCloudType == PlayDecodeMananger.CLOUD_M3U8) {
                    PlayDecodeMananger.setmNeedSysDecoder(!PlayDecodeMananger
                            .ismNeedSysDecoder());
                    // 切换播放器类型然后进行相关请求
                    PlayerUtils.DEFAULT_PLAYER_TYPE = PlayDecodeMananger
                            .getCurrPlayerType();
                    // 如果切换播放器成功了则开始发送请求请求m3u8资源
                    if (changePlayer(PlayerUtils.DEFAULT_PLAYER_TYPE)) {
                        requestCloudPlay(PlayDecodeMananger
                                .getCloudSourceType());
                    } else {
                        if (result != null && !TextUtils.isEmpty(result.getAllCloudData())) {
                            reportPlayState(MoviesConstant.GET_PLAYURL_FAIL_STATE, MoviesConstant.SUCCESS_NO_URL, result.getAllCloudData());
                        } else {
                            reportPlayState(MoviesConstant.GET_PLAYURL_FAIL_STATE, MoviesConstant.SUCCESS_NO_DATA, "");
                        }
                    }
                }
            }
        }

        @Override
        public void onPreRequest() {

        }

        @Override
        public boolean onRequestFailed(String code, String msg) {
            mPlayStatusReport.setEndRequestTime(System.currentTimeMillis());
            if ("503".equals(code)) {
                reportPlayState(MoviesConstant.GET_PLAYURL_FAIL_503, "", "");
            } else if ("211".equals(code)) {
                reportPlayState(MoviesConstant.GET_PLAYURL_FAIL_211, "", "");
            } else if ("212".equals(code)) {
                reportPlayState(MoviesConstant.GET_PLAYURL_FAIL_212, "", "");
            } else if (MoviesConstant.RESPONSE_DATA_ERROR.equals(code)) {
                reportPlayState(MoviesConstant.GET_PLAYURL_FAIL_STATE, "", msg);
            } else {
                mPlayStatusReport.setmHttpCode(code);
                reportPlayState(MoviesConstant.GET_PLAYURL_FAIL_STATE, code, "");
            }
            cloudDiskError();
            return false;
        }
    }

    private void handleCDECloudUrl() {
        if (mCloudPlayPosition < mCloudPlayUrls.size()) {
            String cloudPlayUrl = mCloudPlayUrls
                    .get(mCloudPlayPosition);
            String resultUrl = "";
            CdeHelper cdeHelper = mCDEManager.getmCdeHelper();
            // 判断当前CDE服务是否启动
            if (cdeHelper.isReady()) {
                LogCat.e(TAG, "!!!!!!!CDE服务是启动的");
                if (!TextUtils.isEmpty(cloudPlayUrl)) {
                    mInSiteRetryTime = 3; //请求成功直接设置为3，无需重试
                    LogUtils.e(TAG, "!!!!!!!!!!!!!!!!!!!!!request cloud play data sucess and cloudPlayUrl is " + cloudPlayUrl);
                    LogCat.e("wym", "cloud cde called and cur uuid " + bigDataPlayReporter.getUUID());
                    bigDataPlayReporter.genUUID(); // 在拿到cde调度地址时，构造当前播放器uuid
                    LogCat.e("wym", "!!!!!!!!!!!!!!!!!!!!!before addPlatCode cloudPlayUrl is " + cloudPlayUrl);
                    String uuid = bigDataPlayReporter.getUUID();
                    String vid = mPlayEpisode.getCloudId(); // vid取cloudId
                    LogCat.e("wym", "!!!!!!!!!!!!!!uuid is " + uuid + " and cloudid is " + vid);
                    LogCat.e("wym", "!!!!!!!!!!!!!!mid is " + mPlayEpisode.getMid() + " and vid is " + mPlayEpisode.getVid() + " and gvid is " + mPlayEpisode.getGlobaVid());
                    // add platParam && (add uuid,vid || uuid,liveid)
                    cloudPlayUrl = PlayerUtils
                            .addPlatCode(cloudPlayUrl, uuid, vid);
                    LogCat.e("wym", "!!!!!!!!!!!!!!!!!!!!!after addPlatCode cloudPlayUrl is " + cloudPlayUrl + cdeHelper.getServiceVersion());
                    // CdeHelper cdeHelper =
                    // mCDEManager.getmCdeHelper();
                    mLinkShellUrl = cdeHelper.getLinkshellUrl(cloudPlayUrl);
                    LogCat.e("wym", "$$$$$$$$mLinkShellUrl$$$$$$" + mLinkShellUrl);
                    resultUrl = cdeHelper.getPlayUrl(mLinkShellUrl);
                }
                if (!StringUtil.isEmpty(resultUrl)) {
                    LogCat.e("wym", "云盘cdeurl-----------" + resultUrl);
                    doPlay(PlayerUtils.DEFAULT_PLAYER_TYPE, resultUrl);
                }
            } else {
                mCdeStatusReiver = new CDEStatusReceiver();
                mSelfOwnActivity.registerReceiver(mCdeStatusReiver,
                        new IntentFilter(CdeService.ACTION_CDE_READY));
                mCDEManager.startCde();
            }
        }
    }

    public class CloudErrorListener implements
            RequestResultListener<CloudErrorBean> {

        @Override
        public boolean onRequestFailed() {
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, CloudErrorBean result) {
            LogCat.e("", "report will start");
            String needReport = "1";
            if (result != null && needReport.equals(result.getShouldReport()) &&
                    result.getErrorBeans() != null) {
                PostCloudErrorBean postCloudErrorBean = Utils.genetateCloudErrorData();
                postCloudErrorBean.getApp().setSplatid(Uri.parse(mCloudPlayUrls
                        .get(mCloudPlayPosition)).getQueryParameter("splatid"));
                SharedPreferences sharedPreferences =
                        MoviesApplication.getInstance().getSharedPreferences(
                                SettingManage.LOGIN_INFO, Context.MODE_PRIVATE);
                if (!sharedPreferences.getString("uid", "").isEmpty()) {
                    postCloudErrorBean.getUser().setUid(sharedPreferences.getString("uid", ""));
                    postCloudErrorBean.getUser().setType("register");
                } else {
                    postCloudErrorBean.getUser().setUid("");
                }
                postCloudErrorBean.getResource().setName(mVideoName);
//                try {
//                    postCloudErrorBean.getResource().setName(new String((mVideoName).getBytes("gbk"), "utf-8"));
//                } catch (UnsupportedEncodingException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
                ArrayList<MsgBean> msg = new ArrayList<>();
                for (int i = 0; i < result.getErrorBeans().size(); i++) {
                    MsgBean msgBean = new MsgBean();
                    msgBean.setPhase("query resource");
                    msgBean.setData(result.getErrorBeans().get(i).getInfo());
                    msgBean.setUrl(result.getErrorBeans().get(i).getUrl().toString());
                    msgBean.setCode(result.getErrorBeans().get(i).getCode());
                    msg.add(msgBean);
                }
                postCloudErrorBean.setMsg(msg);
                if (MoviesApplication.getInstance() != null) {
                    new PostCloudErrorDataTask(MoviesApplication.getInstance(), postCloudErrorBean).start();
                }
            }

        }

        @Override
        public void onPreRequest() {

        }
    }

    /**
     * 显示当前网速 zhangshuo 2014年8月19日 下午2:12:27
     */
    private void showNetRate() {
        // 如果当前API level > 2.2则显示当前网速
        if (Utils.getAPILevel() >= PlayerUtils.API_8) {
            String currentRate = TrafficStatsUtil.countCurRate();
            mNetRate.setVisibility(View.VISIBLE);
            mNetRate.setText("加载中: " + currentRate);
        } else {
            mNetRate.setVisibility(View.INVISIBLE);
        }
    }

    public void setmSnifferParamter(String mSnifferParamter) {
        this.mSnifferParamter = mSnifferParamter;
    }

    /**
     * 根据当前清晰度获取url
     *
     * @param playMap
     * @return
     */
    public String getUrlByClarity(HashMap<String, String> playMap) {
        String playUrl = "";
        if (null != playMap && playMap.size() > 0) {
            playUrl = playMap.get(mDefaultDefinition);
            if (TextUtils.isEmpty(playUrl)) {
                if (PlayerUtils.SMOOTHURL.equals(mDefaultDefinition)) {
                    mDefaultDefinition = PlayerUtils.STANDARDURL;
                    playUrl = playMap.get(mDefaultDefinition);
                } else if (PlayerUtils.STANDARDURL.equals(mDefaultDefinition)) {
                    mDefaultDefinition = PlayerUtils.SMOOTHURL;
                    playUrl = playMap.get(mDefaultDefinition);
                } else if (PlayerUtils.HIGHURL.equals(mDefaultDefinition)) {
                    mDefaultDefinition = PlayerUtils.STANDARDURL;
                    playUrl = playMap.get(mDefaultDefinition);
                    if (TextUtils.isEmpty(playUrl)) {
                        getUrlByClarity(playMap);
                    }
                } else if (PlayerUtils.SUPERURL.equals(mDefaultDefinition)) {
                    mDefaultDefinition = PlayerUtils.HIGHURL;
                    playUrl = playMap.get(mDefaultDefinition);
                    if (TextUtils.isEmpty(playUrl)) {
                        getUrlByClarity(playMap);
                    }
                }
            }
        } else {
            playUrl = "";
        }
        return playUrl;
    }

    private class CDEStatusReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (null == intent) {
                return;
            }

            if (CdeService.ACTION_CDE_READY.equals(intent.getAction())) {
                unRegisterReceiver();

                if (!PlayerUtils.SITE_CLOUDDISK.equals(mPlayData.getSite())) {
                    isCloud = false;
                    // 如果CDE已经准备就绪则开始执行内网播放逻辑
                    executeInSiteProcess();
                } else {
                    isCloud = true;
                    // 如果CDE已经准备就绪则开始执行外网播放逻辑中的云盘播放
                    executeOutSiteProcess();
                }
            }
        }
    }

    public void unRegisterReceiver() {
        if (null != mSelfOwnActivity && null != mCdeStatusReiver) {
            mSelfOwnActivity.unregisterReceiver(mCdeStatusReiver);
            mCdeStatusReiver = null;
        }
        if (mSelfOwnActivity != null) {
            if (timeReceiver != null) {
                try {
                    mSelfOwnActivity.unregisterReceiver(timeReceiver);
                } catch (Exception e) {
                    LogUtils.e("Not register receiver");
                }
            }
            if (batteryChangedReceiver != null) {
                try {
                    mSelfOwnActivity.unregisterReceiver(batteryChangedReceiver);
                } catch (Exception e) {
                    LogUtils.e("Not register receiver");
                }
            }
        }
    }

    private boolean isEpisodeFirst() {
        ArrayList<String> porderList = mPlayData.getmPorderLists();
        if (null != porderList && null != mEpisodes) {
            Episode episode = mEpisodes.get(0);
            if (episode.getPorder().equals(porderList.get(0))) {
                return true;
            }
        }
        return false;
    }

    private boolean isEpisodeEnd() {
        ArrayList<String> porderList = mPlayData.getmPorderLists();
        if (null != porderList && null != mEpisodes) {
            int proderSize = porderList.size();
            int episodeSize = mEpisodes.size();
            Episode episode = mEpisodes.get(episodeSize - 1);
            if (episode.getPorder().equals(porderList.get(proderSize - 1))) {
                return true;
            }
        }
        return false;
    }

    /**
     * 根据site设置本地播放 mid和owner
     *
     * @param localVideoEpisode
     */
    private void setReportMid(LocalVideoEpisode localVideoEpisode) {
        LogCat.e(TAG, "setReportMid cur localVideoEpisode info is " + localVideoEpisode);
        String site = localVideoEpisode.getSite();
        bigDataPlayReporter.setOwner(BigDataConstants.OWNER_IN);
        bigDataPlayReporter.setSource(site);
        if (PlayerUtils.SIET_LETV.equals(site)) {
            if (!TextUtils.isEmpty(localVideoEpisode.getLVideoMid()))
                bigDataPlayReporter.setMid(localVideoEpisode.getLVideoMid());
            else
                bigDataPlayReporter.setMid(localVideoEpisode.getMid());
            if (TextUtils.isEmpty(localVideoEpisode.getMid()))
                bigDataPlayReporter.setMid(localVideoEpisode.getId());
        } else if (PlayerUtils.SITE_CLOUDDISK.equals(site)) {
            bigDataPlayReporter.setOwner(BigDataConstants.OWNER_OUT);
            if (!TextUtils.isEmpty(localVideoEpisode.getCloudId()))
                bigDataPlayReporter.setMid(localVideoEpisode.getCloudId());
            else
                bigDataPlayReporter.setMid(localVideoEpisode.getId());
        } else {
            bigDataPlayReporter.setOwner(BigDataConstants.OWNER_OUT);
            if (!TextUtils.isEmpty(localVideoEpisode.getGlobaVid()))
                bigDataPlayReporter.setMid(localVideoEpisode.getGlobaVid());
            else
                bigDataPlayReporter.setMid(localVideoEpisode.getId());
        }
    }

    /**
     * 新外网截流
     */
    private void requestOutSiteStreamInfo(List<String> apiContent) {
        // 执行除云盘之外的其他站点的逻辑
        mOutSiteStreamInfoTask = new RequestOutSiteStreamInfoTask(MoviesApplication.getInstance());
        if (null != mOutSiteStreamInfoTask && !mOutSiteStreamInfoTask.isCancelled()) {
            mOutSiteStreamInfoTask.cancel();
        }

        mIsSdkPlayer = false;
        mPlayStatusReport = new PlayStatusReporter();
        mPlayStatusReport.setAction(MoviesConstant.STATE_ACTION_PLAY);
        mPlayStatusReport.setPorder(mPlayEpisode.getPorder());
        mPlayStatusReport.setVid(mSnifferUrl);
        mPlayStatusReport.setExternal_id(mPlayEpisode.getExternalId());
        mPlayStatusReport.setGlobal_vid(mPlayEpisode.getGlobaVid());
        String site = TextUtils.isEmpty(mPlayEpisode.getSite()) ? mPlayData.getSite() : mPlayEpisode.getSite();
        mPlayStatusReport.setSubsrc(site);
        mPlayStatusReport.setSrartRequestTime(System.currentTimeMillis());
        mPlayStatusReport.setAid(mReportAid);
        if (mPlayData != null) {
            mPlayStatusReport.setVt(mPlayData.getVt());
        }

        mOutSiteStreamInfoTask.setType(Utils.STREAM_PLAY);
        mOutSiteStreamInfoTask.setUrl(mSnifferUrl);
        mOutSiteStreamInfoTask.setFormats(mOutsiteClarity);
        if (apiContent != null) {
            mOutSiteStreamInfoTask.setApiContent(apiContent);
        } else {
            isSpecialSniff = false;
        }
        OutSiteStreamInfoRequestListener outSiteStreamInfoRequestListener = new OutSiteStreamInfoRequestListener();
        outSiteStreamInfoRequestListener.setCurrentSite(site);
        mOutSiteStreamInfoTask.setListener(outSiteStreamInfoRequestListener);
        mOutSiteStreamInfoTask.start();
        LogCat.e(TAG, "!!!!!!!!!!!!!!!!!!!mOutSiteStreamInfoTask start!!!!!!!!!!!!!!!!!!!");
        UmengEventPoster.doEventPost(UmengPostConstant.PlayVideo_other); //播外站源友盟上报
        if("letv".equals(site)){
            MoviesConstant.letvPlayStatus = 2;
        }
    }

    public class OutSiteStreamInfoRequestListener implements
            NewRequestResultListener<OutSiteStreamInfo> {

        String site = "";

        public void setCurrentSite(String currentSite) {
            site = currentSite;
        }

        @Override
        public boolean onRequestFailed() {
            LogCat.e(Utils.TAG, "!!!!!!!!!OutSiteStreamInfo requestFailed and default goWebPlay!!!!!!!!!");
            mPlayStatusReport.setRetry("" + retryTime);
            mPlayStatusReport.setEndRequestTime(System.currentTimeMillis());
            reportPlayState(MoviesConstant.SERVER_PLAY_RESULT_ERROR, "", "");
            if("0".equals(SharePreferenceManager.getVaule(mSelfOwnActivity, SharePreferenceManager.FAILOVERPLAYTYPE, "1"))){
                excuteLetvProcess();
            }else if (site.equals(mPlayData.getSite())) {
                jumpToWebPlayeActivity();
            }
            return false;
        }

        @Override
        public boolean onNoNet() {
            setPlayLoadingVisibile(false);
            mPlayStatusReport.setRetry("" + retryTime);
            mPlayStatusReport.setEndRequestTime(System.currentTimeMillis());
            reportPlayState(MoviesConstant.SERVER_PLAY_NETS_ERROR, "", "");
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, OutSiteStreamInfo result) {
            mPlayStatusReport.setEndRequestTime(System.currentTimeMillis());
            LogCat.e(Utils.TAG, "onRequestSuccess method OutSiteStreamInfo is " + result);
            if (result == null) {
                isNeedRetry = true;
            } else {
                isNeedRetry = checkIsNeedRetry(result);
            }
            LogCat.e(Utils.TAG, "onRequestSuccess method end and final isNeedRetry is " + isNeedRetry);
            mPlayStatusReport.setRetry("" + retryTime);
            if (isNeedRetry) {
                if (retryTime < 2) {
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            LogCat.e(Utils.TAG, "first again try request OutSiteStreamInfo");
                            retryTime++;
                            if (site.equals(mPlayData.getSite())) {
                                if (mApi_contentlist != null && mApi_contentlist.size() > 0) {
                                    requestOutSiteStreamInfo(mApi_contentlist);
                                } else {
                                    requestOutSiteStreamInfo(null);
                                }
                            }
                        }
                    }, 1500);
                } else if (retryTime == 2) {
                    excuteUpdatestreamTask();
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            LogCat.e(Utils.TAG, "first again try request OutSiteStreamInfo");
                            retryTime++;
                            if (site.equals(mPlayData.getSite())) {
                                if (mApi_contentlist != null && mApi_contentlist.size() > 0) {
                                    requestOutSiteStreamInfo(mApi_contentlist);
                                } else {
                                    requestOutSiteStreamInfo(null);
                                }
                            }
                        }
                    }, 1500);
                } else {
                    LogCat.e(Utils.TAG, "second try request OutSiteStreamInfo not allowed");
                    //TODO 所有stream_list都为空（但此时api_list不为空也无需考虑，直接跳web）
                    mPlayStatusReport.setEndRequestTime(System.currentTimeMillis());
                    reportPlayState(MoviesConstant.GET_PLAYURL_FAIL_STATE, "", "");
                    if("0".equals(SharePreferenceManager.getVaule(mSelfOwnActivity, SharePreferenceManager.FAILOVERPLAYTYPE, "1"))){
                        excuteLetvProcess();
                    }else if (site.equals(mPlayData.getSite())) {
                        jumpToWebPlayeActivity();// data null err
                    }
                }
            } else {
                if (result != null) {
                    videoCaseList = result.getAllFormatsList();
                    mClaritymap = DefinitionManager.getSupportDefFlag(result.getAllFormatsList());
                    DefinitionManager.DefinitionObj definitionObj
                            = DefinitionManager.checkDefClassify(mOutsiteClarity);

                    if (definitionObj != null && mClaritymap.containsKey(definitionObj.defType)
                            && mClaritymap.get(definitionObj.defType)) {
                        executeOutSitePlayCore2(result);
                    } else {
                        retryTime = 0;
                        if (mClaritymap.get(DefinitionManager.DEFINITION_TYPE_FLUENCY)) {
                            changeOuterDefinition(DefinitionManager.DEFINITION_TYPE_FLUENCY, PlayerUtils.VT_MP4);
                        } else if (mClaritymap.get(DefinitionManager.DEFINITION_TYPE_NORMAL)) {
                            changeOuterDefinition(DefinitionManager.DEFINITION_TYPE_NORMAL, PlayerUtils.VT_MP4_350);
                        } else if (mClaritymap.get(DefinitionManager.DEFINITION_TYPE_HIGH)) {
                            changeOuterDefinition(DefinitionManager.DEFINITION_TYPE_HIGH, PlayerUtils.VT_MP4_720p_db);
                        } else if (mClaritymap.get(DefinitionManager.DEFINITION_TYPE_SUPER)) {
                            changeOuterDefinition(DefinitionManager.DEFINITION_TYPE_SUPER, PlayerUtils.VT_MP4_720P);
                        }
                    }
                }
            }
        }

        @Override
        public void onPreRequest() {

        }
    }

    /**
     * 遍历streamEntityQueue列表中每个OutSiteStreamEntity，当且仅当OutSiteStreamEntity的stream_list都为空，则返回true
     *
     * @param streamInfo
     * @return
     */
    private boolean checkIsNeedRetry(OutSiteStreamInfo streamInfo) {
        if (streamInfo.isRetry()) {
            LogCat.e(Utils.TAG, "checkIsNeedRetry method streamInfo newversion is null");
            return true;
        }
        boolean isNeedRetry = false;
        List<OutSiteStreamEntity> list = streamInfo.getStreamEntityQueue();
        if (list != null && list.size() > 0) {
            int size = list.size();
            int count = 0; //list中 stream_list 为空的数量
            for (OutSiteStreamEntity entity : list) {
                if (null != entity && "THREE_PARSES".equals(entity.getClientParseType()) &&
                        null != entity.getApi_list() && entity.getApi_list().size() > 0) {
                    // 无需操作
                } else if (null != entity && null != entity.getStream_list() && entity.getStream_list().size() > 0) {
                    mApi_contentlist = null;
                    // 无需操作
                } else
                    count++;
            }
            if (count == size) {
                isNeedRetry = true;
                LogCat.e(Utils.TAG, "!!!!!!!!!!!!!!! all streamEntity stream_list both is null !!!!!!!!!!!!");
            } else {
                isNeedRetry = false;
                LogCat.e(Utils.TAG, "!!!!!!!!!!!!!!! have stream_list !!!!!!!!!!!!");
            }
        } else
            isNeedRetry = true;
        LogCat.e(Utils.TAG, "checkIsNeedRetry method end and isNeedRetry is " + isNeedRetry);
        return isNeedRetry;
    }

    /**
     * 贴片广告播放
     */

    private void playPasterAd(final String stream) {
        mSelfOwnActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (null != mPlayPasterAdView) {
                    mPlayPasterAdView.setVisibility(View.GONE);
                    mVideoViewPosition.removeView(mPlayPasterAdView);
                }
                if (null != mPlayerView) {
                    mPlayerView.setVisibility(View.GONE);
                    mVideoViewPosition.removeView(mPlayerView);
                }
                mPlayContorl = mVideoViewBuilder.build(mSelfOwnActivity,
                        MyPlayerConstant.MOBILE_PASTER_SDK);
                if ("10".equals(mAttachAdType)) {
                    ((VideoViewPasterProxy) mPlayContorl).createPlayer(MyPlayerConstant.MOBILE_MY_MP4);
                } else {
                    ((VideoViewPasterProxy) mPlayContorl).createPlayer(MyPlayerConstant.MOBILE_MY_PHOTO);
                }
                mPlayPasterAdView = mPlayContorl.getView();
                // 将播放器对象添加至容器中
                RelativeLayout.LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
                params.addRule(RelativeLayout.CENTER_IN_PARENT);

                mVideoViewPosition.addView(mPlayPasterAdView, params);
                LogCat.e(Utils.TAG, "add mPlayerView");
                if (mPlayContorl != null) {
                    ((VideoViewPasterProxy) mPlayContorl).setPlayingAd(true);
                }
                setPlayerListener();
                setAttachAdListener();
                setMediaControllerBottomVisibile(false);
                setMediaControllerTopVisibile(false);
                showVideoPrepareing();
                if ("10".equals(mAttachAdType)) {
                    setVideoUri(stream);
                } else if("11".equals(mAttachAdType)){
                    mXfPayAdView = new XfPayAdView(mSelfOwnActivity, mPlayPasterAdView, "pre-roll");
                    mXfPayAdView.setXfAd(((XfPayload)mPasterAd.payload).ad);
                    if (mPlayContorl != null) {
                        mPlayContorl.start();
                    }
                } else if ("12".equals(mAttachAdType)) {
                    mTtPayAdView = new TtPayAdView(mSelfOwnActivity, mPlayPasterAdView, "pre-roll");
                    mTtPayAdView.setTtAd(((TtPayload)mPasterAd.payload).ad);
                    if (mPlayContorl != null) {
                        mPlayContorl.start();
                    }
                } else {
                    mGdtNativeAdView = new GdtNativeAdView(mSelfOwnActivity,  "attach", mPlayPasterAdView, "pre-roll");
                    mGdtNativeAdView.setAdListener(new MyOnAdListener() {
                        @Override
                        public void onAdDismissed() {

                        }

                        @Override
                        public void onAdFailed() {
                            playVideoAfterAd();
                        }

                        @Override
                        public void onAdPresent() {

                        }

                        @Override
                        public void onAdSuccess(Object obj) {
                            mGdtAdPhotoUri = new ArrayList<>();
                            if (mPlayContorl != null) {
                                mPlayContorl.start();
                            }
                        }
                    });
                    mGdtNativeAdView.loadAD(stream);
                }
            }
        });
    }

    /**
     * 新外网播放
     *
     * @param streamInfo(此时传入的参数一定不为空)
     */
    private void executeOutSitePlayCore2(OutSiteStreamInfo streamInfo) {
        // 开始执行外站源的核心播放逻辑
        mOutSiteStreamInfo = streamInfo;
        mClarityPopupWindow.initCloudClarityUI(mClaritymap, mOutsiteClarity);
        LogCat.e(Utils.TAG, "!!!!!!!!!!!!!!!!!!!!executeOutSitePlayCore method streamInfo is!!!!!!!!!" + streamInfo);
        doPlayLogic2(mCurStreamIndex);
    }

    /**
     * 新流播放主逻辑
     *
     * @param index
     */
    private void doPlayLogic2(int index) {
        isHasRule = false;
        isNeedJsCut = false;
        isQuitSniff = false;
        if (mOutSiteStreamInfo != null) {
            mStreamEntityList = mOutSiteStreamInfo.getStreamEntityQueue();
            if (null == mStreamEntityList) {
                jumpToWebPlayeActivity();
                return;
            }
            int size = mStreamEntityList.size();
            if (index < 0 || index >= size || size <= 0) {
                jumpToWebPlayeActivity();
                return;
            }

            mOutSiteStreamEntity = mStreamEntityList.get(index);
            LogCat.e(Utils.TAG, "curIndex is " + index + " and mOutSiteStreamEntity is " + mOutSiteStreamEntity);
            mAllowFormats = mOutSiteStreamEntity.getAllowFormats();
            mRequestFormat = mOutSiteStreamEntity.getRequestFormat();
            mOsType = mOutSiteStreamEntity.getOsType();
            mEid = mOutSiteStreamEntity.getEid();
            mStream_list = mOutSiteStreamEntity.getStream_list();
            mApi_list = mOutSiteStreamEntity.getApi_list();
            mUser_agent = mOutSiteStreamEntity.getUser_agent();
            getIsHasRule();
            printAllValue(index);
            initOutSiteCalrityView();
            if ("youku".equals(mPlayData.getSite()) && "THREE_PARSES".equals(mOutSiteStreamEntity.getClientParseType()) &&
                    mApi_list != null && !mApi_list.isEmpty() && !isSpecialSniff) {
                isSpecialSniff = true;
                executeSpecialLogic();
                return;
            }

            // 预判断是否需要js截流( mApi_list||rule 为空-->false     mApi_list&&rule 非空-->true)
            if (null != mApi_list && !mApi_list.isEmpty() && isHasRule && mStream_list != null && mStream_list.size() == mApi_list.size() && !isSpecialSniff) {
                LogCat.e(Utils.TAG, "prejudge need jsSniff");
                isNeedJsCut = true;
            } else {
                LogCat.e(Utils.TAG, "prejudge not need jsSniff");
                isNeedJsCut = false;
            }

            if (!TextUtils.isEmpty(mOsType) && OSTYPE_MP4.equalsIgnoreCase(mOsType)) {
                //Mp4 格式
                PlayDecodeMananger.setmNeedSysDecoder(true);
            } else {
                //M3U8 格式
                PlayDecodeMananger.setmNeedSysDecoder(false);
            }
            // 设置播放器类型
            PlayerUtils.DEFAULT_PLAYER_TYPE = PlayDecodeMananger.getCurrPlayerType();
            LogCat.e(Utils.TAG, "cur play type is " + PlayerUtils.DEFAULT_PLAYER_TYPE);
            // 截流逻辑
            if (isNeedJsCut) {
                // 需要截流
                if (mStream_list != null && !mStream_list.isEmpty()) {
                    // 截流  确保每个api都执行请求apiContent
                    mApi_contentlist = new ArrayList();
                    LogCat.e(Utils.TAG, "prepare start sniff");
                    excuteSniffLogic();
                } else {
                    // 切换其他清晰度
                    LogCat.e(Utils.TAG, "!!!!!!!want jsSniff but lack necessary mStream_list param!!!!!!!");
                    LogCat.e(Utils.TAG, "!!!!!!!onlinePlay outsite changeStream!!!!!!!");
                    mCurStreamIndex++;
                    doPlayLogic2(mCurStreamIndex);
                }
            } else {
                // 不需要截流（直接取stream_list来播放）
                LogUtils.e(Utils.TAG, "not need jsSniff and direct play if can or changeStream");
                if (mStream_list != null && !mStream_list.isEmpty()) {
                    //TODO mStream_list可能有多个地址（播放失败，update操作）
                    LogCat.e(Utils.TAG, "!!!!!!!!!doPlay method called!!!!!!!");
                    LogCat.e(Utils.TAG, "!!!!!!!!!cur play definition is " + mRequestFormat);
                    LogCat.e(Utils.TAG, "!!!!!!!!!cur play allow definition is " + mAllowFormats + " " + mStreamIndex);
                    LogCat.e(Utils.TAG, "!!!!!!!!!!!!mStream_list is " + mStream_list + " and size is " + mStream_list.size());
                    mStreamIndex = 0;
                    mIsFirstTime = true;
                    doPlay(PlayerUtils.DEFAULT_PLAYER_TYPE, mStream_list.get(mStreamIndex));
                } else {
                    // 切换其他清晰度
                    LogCat.e(Utils.TAG, "!!!!!!!want direct play but lack necessary mStream_list url!!!!!!!");
                    LogCat.e(Utils.TAG, "!!!!!!!onlinePlay outsite changeStream!!!!!!!");
                    mCurStreamIndex++;
                    doPlayLogic2(mCurStreamIndex);
                }
            }
        } else
            jumpToWebPlayeActivity();
    }

    /**
     *
     */
    private void initOutSiteCalrityView() {
        if (UIs.isScreenOriatationPortrait(mSelfOwnActivity)) {
            mClarity_select.setVisibility(View.GONE);
        } else {
            mClarity_select.setVisibility(View.VISIBLE);
        }
        DefinitionManager.DefinitionObj definitionObj2
                = DefinitionManager.checkDefClassify(mOutsiteClarity);
        if (definitionObj2 != null) {
            mClarity_select.setText(definitionObj2.showTextResId);
        }
    }

    /**
     * 打印当前流实体的参数
     *
     * @param index
     */
    private void printAllValue(int index) {
        LogCat.e(Utils.TAG, "curIndex is " + index + " and all params vaule is {" +
                "allowFormats=" + mAllowFormats +
                ", requestFormat='" + mRequestFormat + '\'' +
                ", osType='" + mOsType + '\'' +
                ", eid='" + mEid + '\'' +
                ", stream_list=" + mStream_list +
                ", api_list=" + mApi_list +
                ", user_agent='" + mUser_agent + '\'' +
                ", isHasRule=" + isHasRule +
                ", te='" + mTe + '\'' +
                ", ts='" + mTs + '\'' +
                '}');
    }

    /**
     * 判断流实体是否有js截流参数
     */
    private void getIsHasRule() {
        if (mOutSiteStreamEntity.isHasRule()) {
            mJsRuleMap = mOutSiteStreamEntity.getRule();
            if (null == mJsRuleMap)
                isHasRule = false;
            else {
                if (mJsRuleMap.isEmpty())
                    isHasRule = false;
                else {
                    mTe = mJsRuleMap.get(TE);
                    mTs = mJsRuleMap.get(TS);
                    if (!TextUtils.isEmpty(mTe) && !TextUtils.isEmpty(mTs))
                        isHasRule = true;
                    else
                        isHasRule = false;
                }
            }
        } else
            isHasRule = false;
    }

    /**
     * 直接使用mStream_list播，或者跳webPlay
     */
    private void handlerOutSiteError2() {
        if (mStream_list != null && !mStream_list.isEmpty()) {
            //TODO mStream_list可能有多个地址（播放失败，update操作）
            LogCat.e(Utils.TAG, "!!!!!!!!!handlerOutSiteError2 method called!!!!!!!");
            LogCat.e(Utils.TAG, "!!!!!!!!!doPlay method called!!!!!!!");
            LogCat.e(Utils.TAG, "!!!!!!!!!cur play definition is " + mRequestFormat);
            LogCat.e(Utils.TAG, "!!!!!!!!!cur play allow definition is " + mAllowFormats);
            LogCat.e(Utils.TAG, "!!!!!!!!!!!!mStream_list is " + mStream_list + " and size is " + mStream_list.size());
            // 播放逻辑切拖，mStream_list可能有多个地址（mp4会存在这种情况），但此时m3u8类型的已经轮询完，不能直接切流（下载mp4优先，可以直接切流）
            mIsJSFailed = true;
            doPlay(PlayerUtils.DEFAULT_PLAYER_TYPE, mStream_list.get(0));
        } else {
            jumpToWebPlayeActivity();
        }
    }

    /**
     * 在切换剧集或者手动点击上，下一集一定要调用
     */
    private void resetOutSiteData() {
        LogCat.e(Utils.TAG, "!!!!!!!!!!resetOutSiteData called!!!!!!!!!!");
        retryTime = 0;
        isNeedRetry = false;
        mCurStreamIndex = 0;
    }

    /**
     * 截流逻辑
     */
    private void excuteSniffLogic() {
        requestSnifferAllApiData();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                circleExcuteSniff();
            }
        }, PlayerUtils.SNIFF_REQUESTAPI_WAITETIME);
    }

    /**
     * 优酷特殊逻辑
     */

    private void executeSpecialLogic() {
        requestSnifferAllApiData();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                RequestSniffDataTaskPoolManager.get().shutdown();
                while (!RequestSniffDataTaskPoolManager.get().isTerminated()) {
                    //等待执行完毕
                    LogCat.e(Utils.TAG, " wait for pool task finish ");
                }
                mApi_contentlist = RequestSniffDataTaskPoolManager.get().getResultList();

                RequestSniffDataTaskPoolManager.get().shutdown();
                if (mApi_contentlist == null || mApi_contentlist.isEmpty()) {
                    LogCat.e(Utils.TAG, " request apiContentList is 0 ！ ");
                    handlerOutSiteError2();
                    return;
                }

                if (mApi_contentlist.size() > 0) {
                    resetOutSiteData();
                    retryTime = 0;
                    requestOutSiteStreamInfo(mApi_contentlist);
                }

            }
        }, PlayerUtils.SNIFF_REQUESTAPI_WAITETIME);
    }

    /**
     * 一次性取到所有截流所需的 apiContent 内容放到 mApi_contentlist中
     */
    private void requestSnifferAllApiData() {
        if (mApi_list != null && !mApi_list.isEmpty()) {
            LogCat.e(Utils.TAG, " js api size is " + mApi_list.size());
            // 多线请求api
            try {
                RequestSniffDataTaskPoolManager.get().createPool();
                RequestSniffDataTaskPoolManager.get().exeTaskTimeOut(mApi_list, mSnifferUrl, mUser_agent, 2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 循环执行本地js截流逻辑
     */
    private void circleExcuteSniff() {
        // 关闭线程池不接受新的任务，如果此时后台                                                                                                                                           有未执行完毕的任务取消掉直接，
        RequestSniffDataTaskPoolManager.get().shutdown();
        while (!RequestSniffDataTaskPoolManager.get().isTerminated()) {
            //等待执行完毕
            LogCat.e(Utils.TAG, " wait for pool task finish ");
        }
        mApi_contentlist = RequestSniffDataTaskPoolManager.get().getResultList();

        RequestSniffDataTaskPoolManager.get().shutdown();
        if (mApi_contentlist == null || mApi_contentlist.isEmpty()) {
            LogCat.e(Utils.TAG, " request apiContentList is 0 ！ ");
            handlerOutSiteError2();
            return;
        }
        if (mStream_list == null || mStream_list.isEmpty()) {
            LogCat.e(Utils.TAG, " request streamList is 0 ！ ");
            handlerOutSiteError2();
            return;
        }
        LogUtils.e(Utils.TAG, " out of time set apicontentList " + mApi_contentlist.size());
        if (mApi_contentlist != null && !mApi_contentlist.isEmpty() && mStream_list != null && !mStream_list.isEmpty()) {
            LogCat.e(Utils.TAG, " send js apicontentList size " + mApi_contentlist.size());
            LogCat.e(Utils.TAG, " send js StreamList size " + mStream_list.size());
            //TODO task to execute cut sniff
//            for (int i = 0; i < mApi_contentlist.size(); i++) {
//                if (isQuitSniff) {
//                    break;
//                }
//                for (int j = 0; j < mStream_list.size(); j++) {
//                    LogUtils.e(Utils.TAG, " send js data (api-content) " + mApi_contentlist.get(i));
//                    LogUtils.e(Utils.TAG, " send js data (stream-list) " + mStream_list.get(j));
//                    if (isQuitSniff) {
//                        break;
//                    }
//                    // TODO 做一个超时逻辑
//                    excuteCoreSniff(mSnifferUrl, mApi_contentlist.get(i), mStream_list.get(j));
//                }
//            }
            excuteCoreSniff(mSnifferUrl, mApi_contentlist, mStream_list);
        } else {
            LogUtils.e(Utils.TAG, " request api out of timeset ！ ");
            handlerOutSiteError2();
        }
    }

    /**
     * @param requestUrl 原始请求的url
     * @param apiContent HttpGet请求api_list 中的每一条数据对应的地址，得到的内容即为apiContent
     * @param streamUrl  stream_list中的每一条数据
     */
    private void excuteCoreSniff(String requestUrl, List<String> apiContent, List<String> streamUrl) {
        if(TextUtils.isEmpty(requestUrl) || apiContent == null || streamUrl == null){
            return;
        }
        JSONObject obj = new JSONObject();
        try {
            obj.put("requestUrl", Base64.encodeToString(requestUrl.getBytes(), Base64.DEFAULT));
            JSONArray array = new JSONArray();
            for (String item : streamUrl) {
                String str = Base64.encodeToString(item.getBytes(), Base64.DEFAULT);
                array.put(str.replace("\\n", ""));
            }
            obj.put("uStream", array);
            array = new JSONArray();
            for (String url : apiContent) {
                if(TextUtils.isEmpty(url)){
                    return;
                }
                String str = Base64.encodeToString(url.getBytes(), Base64.DEFAULT);
                array.put(str.replace("\\n", ""));
            }
            obj.put("apiContent", array);
            // isHasRule一定为true
            if (isHasRule) {
                LogUtils.e(Utils.TAG, " js has rule");
                JSONObject ruleObj = new JSONObject();
                if (!TextUtils.isEmpty(mTs)) {
                    ruleObj.put(TS, mTs);
                }
                if (!TextUtils.isEmpty(mTe)) {
                    ruleObj.put(TE, mTe);
                }
                obj.put("rule", ruleObj);
                LogUtils.e(Utils.TAG, " js rule " + ruleObj.toString());
                LogUtils.e(Utils.TAG, " js ts te (" + mTs + ")  (" + mTe + ")");
            } else {
                LogUtils.e(Utils.TAG, " js no rule");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mSnifferParamter = obj.toString().replace("\\n", "");
        String fileName = "jsSniffRequestParams.html";
        Utils.writeJsSniffLogData(mSelfOwnActivity, fileName, mSnifferParamter);
        LogUtils.e(Utils.TAG, "@@@@@@@" + mSnifferParamter);
        // 发送消息调用JS代码
        mHandler.sendEmptyMessage(Utils.GET_JS_RESULT);
    }

    /**
     * js 解析结果处理，有地址就播放
     *
     * @param result
     */
    private void parseSniffResult2(String result) {
        LogCat.e(Utils.TAG, "Js parse return back !" + result);
        try {
            JSONObject obj = new JSONObject(result);
            // TODO stream串可能有多个地址
            String stream = obj.getString("stream");
            JSONArray array = new JSONObject(result).optJSONArray("stream");
            if (array == null || array.length() == 0) {
                isQuitSniff = false;
                LogCat.e(Utils.TAG, " sniff finish result error");
                handlerOutSiteError2();
                return;
            } else {
                // 本次截流成功
                LogCat.e(Utils.TAG, " sniff finish result ok");
                isQuitSniff = true;
                String fileName = "jsSniffResult.html";
                Utils.writeJsSniffLogData(mSelfOwnActivity, fileName, stream);
                List<String> stream_list = new ArrayList<String>();
                for (int i = 0; i < array.length(); i++) {
                    stream_list.add(array.getString(i));
                }
                excuteUpLoadLocalStreamTask(stream_list);
                mStream_list = stream_list;
                mStreamIndex = 0;
                mIsFirstTime = true;
                mIsJSSuccessed = true;
                doPlay(PlayerUtils.DEFAULT_PLAYER_TYPE, stream_list.get(0));
            }




//            if (!TextUtils.isEmpty(stream)) {
//                LogCat.e(Utils.TAG, " sniff finish result ok");
//                isQuitSniff = true;
//                String fileName = "jsSniffResult.html";
//                Utils.writeJsSniffLogData(mSelfOwnActivity, fileName, stream);
//                LogCat.e(Utils.TAG, "!!!!!!!!!!!!!!!!js sniff sucess!!!!!!!!!!!!!!!!!!");
//                LogCat.e(Utils.TAG, "!!!!!!!!!doPlay method called!!!!!!!");
//                LogCat.e(Utils.TAG, "!!!!!!!!!cur play definition is " + mRequestFormat);
//                LogCat.e(Utils.TAG, "!!!!!!!!!cur play allow definition is " + mAllowFormats);
//                LogCat.e(Utils.TAG, "!!!!!!!!!cur play stream is " + stream);
//                //  截流成功上报（播放截流遇到多个apiList没有处理，下载已经处理）
//                List<String> stream_list = new ArrayList<String>();
//                stream_list.add(stream);
//                excuteUpLoadLocalStreamTask(stream_list);
//                doPlay(PlayerUtils.DEFAULT_PLAYER_TYPE, stream);
//            } else {
//                // 本次截流失败
//                isQuitSniff = false;
//                LogCat.e(Utils.TAG, " sniff finish result error");
//                handlerOutSiteError2();
//            }
        } catch (Exception e) {
            e.printStackTrace();
            LogCat.e(Utils.TAG, "Js parse result err");
            handlerOutSiteError2();
        }
    }

    /**
     * 截流成功上报
     */
    private void excuteUpLoadLocalStreamTask(List<String> stream_list) {
        if (null != mUpLoadLocalStreamTask && !mUpLoadLocalStreamTask.isCancelled())
            mUpLoadLocalStreamTask.cancel();
        mUpLoadLocalStreamTask = new UpLoadLocalStreamTask(MoviesApplication.getInstance(), mAllowFormats, mRequestFormat, mOsType, mSnifferUrl);
        mUpLoadLocalStreamTask.setStream_list(stream_list);
        mUpLoadLocalStreamTask.setListener(new UpLoadLocalStreamListener());
        mUpLoadLocalStreamTask.start();
    }

    private class UpLoadLocalStreamListener implements RequestResultListener<UpLoadLocalStreamBean> {
        @Override
        public boolean onRequestFailed() {
            LogCat.e(Utils.TAG, "!!!!!!!!!!!UpLoadLocalStream fail!!!!!!!!!!!!!!!!!!");
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, UpLoadLocalStreamBean result) {
            if (null != result)
                LogCat.e(Utils.TAG, "!!!!!!!!!!!UpLoadLocalStream sucess!!!!!!!!!!!!!!!!!!");
            else
                LogCat.e(Utils.TAG, "!!!!!!!!!!!UpLoadLocalStream fail!!!!!!!!!!!!!!!!!!");
        }

        @Override
        public void onPreRequest() {

        }
    }

    /**
     * 码流更新接口
     */
    private void excuteUpdatestreamTask() {
        if (null != mUpdatestreamTask && !mUpdatestreamTask.isCancelled())
            mUpdatestreamTask.cancel();
        mUpdatestreamTask = new UpdatestreamTask(MoviesApplication.getInstance(), mSnifferUrl);
        mUpdatestreamTask.setEid(mEid);
        mUpdatestreamTask.setState(PLAY_FAIL);
        mUpdatestreamTask.setListener(new UpdatestreamListener());
        mUpdatestreamTask.start();
    }

    private class UpdatestreamListener implements RequestResultListener<UpdatestreamBean> {
        @Override
        public boolean onRequestFailed() {
            LogCat.e(Utils.TAG, "!!!!!!!!!!!Updatestream fail!!!!!!!!!!!!!!!!!!");
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, UpdatestreamBean result) {
            if (null != result)
                LogCat.e(Utils.TAG, "!!!!!!!!!!!Updatestream sucess!!!!!!!!!!!!!!!!!!");
            else
                LogCat.e(Utils.TAG, "!!!!!!!!!!!Updatestream fail!!!!!!!!!!!!!!!!!!");
        }

        @Override
        public void onPreRequest() {

        }
    }

    /**
     * 判断是否是乐视源
     *
     * @return
     */
    private boolean isLVideoSource() {
        boolean isLVideo = false;
        String site = "";
        if (null != mPlayData)
            site = mPlayData.getSite();
        if (!TextUtils.isEmpty(site)) {
            if (null != mPlayEpisode && !TextUtils.isEmpty(mPlayEpisode.getMid())) {
                isLVideo = true;
            }
            if (PlayerUtils.SITE_CLOUDDISK.equals(site)) {
                isLVideo = true;
            }
        }
        return isLVideo;
    }

    private void prepareTotalTime() {
        LogCat.e(TAG, "prepareTotalTime");
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (mStream_list != null && mStream_list.size() > 1 && mIsFirstTime) {
                    mDuration = 0;
                    mSelfOwnActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mTotalTime.setText("");
                        }
                    });
                    mStreamListTime = new ArrayList<>();
                    mIsLoadAllPiece = false;
                    mIsFirstTime = false;
                    if (mOutSiteStreamEntity != null && mOutSiteStreamEntity.getDurationList() != null &&
                            mOutSiteStreamEntity.getDurationList().size() > 0 && !TextUtils.isEmpty(mOutSiteStreamEntity.getTotalDuration())) {
                        try {
                            mDuration = (long) (Double.parseDouble(mOutSiteStreamEntity.getTotalDuration()) * 1000);
                        } catch (Exception e) {
                            mDuration = 0;
                        }
                        try {
                            for (int i = 0; i < mOutSiteStreamEntity.getDurationList().size(); i++) {
                                mStreamListTime.add((int) (Double.parseDouble(mOutSiteStreamEntity.getDurationList().get(i)) * 1000));
                            }

                        } catch (Exception e) {
                        }
                        mIsLoadAllPiece = true;
                        mHandler.sendEmptyMessage(Utils.TIME_REFRESH);
                    } else {
                        for (int i = 0; i < mStream_list.size(); i++) {
                            try {
                                final MediaPlayer mediaPlayer = new MediaPlayer();
                                final int time = i;
                                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                                mediaPlayer.setDataSource(mSelfOwnActivity, Uri.parse(mStream_list.get(i)));
                                mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
                                    @Override
                                    public void onPrepared(MediaPlayer mp) {
                                        if (time == 0) {
                                            mDuration = 0;
                                        }
                                        mStreamListTime.add(new Integer(mp.getDuration()));
                                        mDuration += mp.getDuration();
                                        // 设置影片总长
                                        mHandler.sendEmptyMessage(Utils.TIME_REFRESH);
                                        mp.release();
                                        if (time == mStream_list.size() - 1) {
                                            mIsLoadAllPiece = true;
                                        }
                                    }
                                });
                                mediaPlayer.prepare();
                            } catch (Exception e) {
                                LogCat.e(TAG, "AA " + e);
//                            prepareTotalTime();
                            }
                        }
                    }

                } else if (mIsFirstTime) {
                    mIsFirstTime = false;
                    mDuration = mPlayContorl.getDuration();
                    mIsLoadAllPiece = true;
                    mHandler.sendEmptyMessage(Utils.TIME_REFRESH);
                }
            }
        }).start();
    }

    private void doPlayLocalVideo(String playUrl) {
        // 根据当前的播放器类型创建播放器View
        if (null != mPlayerView) {
            mPlayerView.setVisibility(View.GONE);
            mVideoViewPosition.removeView(mPlayerView);
        }
        // 获取播放器的Controller
        mPlayContorl = mVideoViewBuilder.build(mSelfOwnActivity,
                PlayerUtils.DEFAULT_PLAYER_TYPE);
        // 将播放器对象添加至容器中
        mPlayerView = mPlayContorl.getView();
        RelativeLayout.LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        params.addRule(RelativeLayout.CENTER_IN_PARENT);
        mVideoViewPosition.addView(mPlayerView, params);
        setPlayerListener();
        if (!TextUtils.isEmpty(playUrl)) {
            playUrl = playUrl.replace(" ", "%20");
            setVideoUri(playUrl);
        }
    }

    public void setDataPlayTs(long reTime) {
        mPlayPeriod = mPlayDataReport.new PlayPeriod();
        mPlayPeriod.setAbPlayTs(System.currentTimeMillis());
        mPlayPeriod.setRePlayTs(reTime);
    }

    public void setDataPauseTs(long reTime) {
        if (mPlayPeriod != null) {
            mPlayPeriod.setAbPauseTs(System.currentTimeMillis());
            mPlayPeriod.setRePauseTs(reTime);
            mPlayDataReport.addPlayPeriod(mPlayPeriod);
            mPlayPeriod = null;
        }
    }

    public void setHalfScreenView(boolean isFull) {
        mIsFullScreen = isFull;
        requestPauseAd();
        if (Utils.getAPILevel() >= PlayerUtils.API_14) {
            mWindow = mSelfOwnActivity.getWindow();
            if (isFull) {
                statusBarShow(false);//从半屏切换到全屏时，隐藏状态栏
                mSystemInfoViewLayout.setVisibility(View.VISIBLE);
            } else {
                statusBarShow(true);
                mSystemInfoViewLayout.setVisibility(View.GONE);
            }
        }
        if (isFull) {
            mSwitchScreenIv.setVisibility(View.GONE);
            if(mSelfOwnActivity instanceof PlayActivitySelfOwn){
                mClarity_select.setVisibility(View.GONE);
            }else{
                mClarity_select.setVisibility(View.VISIBLE);
            }
            if (isNeedShowNext) {
                mPlayNextBtn.setVisibility(View.VISIBLE);
            } else {
                mPlayNextBtn.setVisibility(View.GONE);
            }
            if (mPlayData != null && MoviesConstant.VT_MOVIE.equals(mPlayData.getVt())) {
                setSelectVisibile(false);
                setNextBtnVisibile(false);
            } else {
                setSelectVisibile(true);
                setSelectClickable(true);
            }
            if (mGestureHandle != null && mPlayPositionView != null) {
                mGestureHandle.dismissGesturePopupWindow();
                if (mGestureHandle.isGestureGuidePopupWindowShow()) {
                    mGestureHandle.dismissGestureGuideView();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mGestureHandle.setmFullScreenLayout(mPlayPositionView);
                            mGestureHandle.showGestureGuideView(false);
                        }
                    }, 500);
                }

            }
            reportCutFullScreen();
        } else {
            mSwitchScreenIv.setVisibility(View.VISIBLE);
            mPlayNextBtn.setVisibility(View.GONE);
            mClarity_select.setVisibility(View.GONE);
            mSelectBtn.setVisibility(View.GONE);
            mClarityPopupWindow.disMissPopView();
            setSelectLayoutVisibile(false);
            setSelectVisibile(false);
            if (mGestureHandle != null && mPlayPositionView != null) {
                mGestureHandle.dismissGesturePopupWindow();
                if (mGestureHandle.isGestureGuidePopupWindowShow()) {
                    mGestureHandle.dismissGestureGuideView();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mGestureHandle.setmFullScreenLayout(mPlayPositionView);
                            mGestureHandle.showGestureGuideView(false);
                        }
                    }, 500);
                }

            }
        }
    }

    private void reportPlayState(String state, String httpcode, String response) {
        mPlayStatusReport.setmHttpCode(httpcode);
        mPlayStatusReport.setmResponsedata(response);
        mPlayStatusReport.setState(state);
        if (mPlayEpisode != null && !TextUtils.isEmpty(mPlayEpisode.getCloudId())) {
            mPlayStatusReport.setmCloudId(mPlayEpisode.getCloudId());
        }
        PlayStatusReporter playStatus = null;
        try {
            playStatus = mPlayStatusReport.clone();
        } catch (CloneNotSupportedException e) {

        }
        new ReportPlayStatusTask(MoviesApplication.getInstance(), playStatus).start();
    }

    private void reportCutFullScreen() {
        if (mIsFirstTimeFullScreen) {
            Map<String, String> dataMap = BigDataApi.createDataMap("0", "eventId=fullscreen", "", "", "", "");
            if (bigDataPlayReporter != null) {
                dataMap.put("uuid", bigDataPlayReporter.getUUID());
            }
            BigDataApi.bigDataCommonReport(dataMap, mSelfOwnActivity);
            mIsFirstTimeFullScreen = false;
        }
    }

    private int getNextStep() {
        int nextStep = 0;
        if (mCurrentStep == 0) {
            nextStep = FIRST_STEP;
        } else if (mCurrentStep == FIRST_STEP) {
            nextStep = SECOND_STEP;
        } else {
            nextStep = OTHER_STEP;
        }
        return nextStep;
    }

    private int getNextStepTime() {
        int time = FIRST_STEP_TIME;
        int nextStep = getNextStep();
        if (nextStep == FIRST_STEP) {
            time = FIRST_STEP_TIME;
        } else if (nextStep == SECOND_STEP) {
            time = SECOND_STEP_TIME;
        } else {
            time = OTHER_STEP_TIME;
        }
        Log.i("gggggggggggggg", time + "");
        return time;
    }

    private void reporterTime() {
        long now = System.currentTimeMillis();
        long diff = now - mTimeMillis;
        mTimeMillis = now;
        int seconds = (int) (diff / 1000);
        if (bigDataPlayReporter != null && seconds > 0) {
            bigDataPlayReporter.setPt(seconds);
            bigDataPlayReporter.onPlayTime();
            addStep();
        }
    }

    private void addStep() {
        mCurrentStep++;
    }

    // 乐视player行为统计
    public void LetvPlayerStatistics(int action) {
        if (mPlayData == null || mPlayEpisode == null) {
            return;
        }
        if (Constants.SDK_LETV.equals(mPlayData.getPlayer()) && !TextUtils.isEmpty(mPlayEpisode.getExternalId()) && 1 == MoviesConstant.letvPlayStatus) {
            mLetvPlayer = LetvPlayer.getInstance(MoviesApplication.getInstance());
            switch (action) {
                case Constants.LETV_PLAY_ACT_ON_RESUME:
                    if (mLetvPlayer != null && mLetvPlayer.mPlayerView != null) {
                        mLetvPlayer.onResume();
                    }
                    break;
                case Constants.LETV_PLAY_ACT_ON_DESTROY:
                    if (mLetvPlayer != null ) {
                        mLetvPlayer.onDestroy();
                    }
                    break;
                case Constants.LETV_PLAY_ACT_ON_PAUSE:
                    if (mLetvPlayer != null && mLetvPlayer.mPlayerView != null) {
                        mLetvPlayer.onPause();
                    }
                    break;
                case Constants.LETV_PLAY_ACT_ON_STOP:
                    if (mLetvPlayer != null) {
                        mLetvPlayer.onStop();
                    }
                    break;
            }
        }
    }

    public void requestPasterAd() {
        mRequestAdTask = new RequestAdTask(MoviesApplication
                .getInstance(), MoviesHttpApi.ATTACH, mPlayData.getSite(), new PasterAdRequestResultListener());
        mRequestAdTask.start();
    }

    public void requestPauseAd(){
        if(!mIsPause || mIsPlayLocalUrl){
            pauseAdLayout.setVisibility(View.GONE);
            return;
        }
        if (mPauseAd == null) {
            mRequestAdTask = new RequestAdTask(MoviesApplication
                    .getInstance(), MoviesHttpApi.PAUSE, new AdRequestResultListener());
            mRequestAdTask.start();
        } else {
            showPauseAd();
        }
    }
    // 重写原因是：返回失败时无法判断是哪一种类型广告
    private class PasterAdRequestResultListener implements
            RequestResultListener<NewAdDataBean> {

        @Override
        public boolean onRequestFailed() {
            if(Constants.SDK_LETV.equals(mPlayData.getPlayer()) && !TextUtils.isEmpty(mPlayEpisode.getExternalId()) && 1 == MoviesConstant.letvPlayStatus){
                doLetvSdkPlay();
            } else if (Constants.SDK_PPTV.equals(mPlayData.getPlayer()) && !TextUtils.isEmpty(mPlayEpisode.getExternalId())) {
                doPptvSdkPlay();
            } else {
                doTruePlay();
            }
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, NewAdDataBean result) {
            mPasterAd = result;
            if(mPasterAd != null){
                AdRequestStatis.selfResponseReport(result, SelfDataConstant.AD_PO_PREROLL);
            }
            if (result != null && "10".equals(result.provider)) {
                mAttachAdType = "10";
                playPasterAd(((HzPayload)mPasterAd.payload).ad.src);
            } else if (result != null && "7".equals(result.provider)) {
                mAttachAdType = "7";
                playPasterAd(((SDKPayload)mPasterAd.payload).adId);
            } else if(result != null && "11".equals(result.provider)){
                mAttachAdType = "11";
                playPasterAd("");
            } else if (result != null && "12".equals(result.provider)) {
                mAttachAdType = "12";
                playPasterAd("");
            }else {
                if(Constants.SDK_LETV.equals(mPlayData.getPlayer()) && !TextUtils.isEmpty(mPlayEpisode.getExternalId())&& 1 == MoviesConstant.letvPlayStatus){
                    doLetvSdkPlay();
                } else if (Constants.SDK_PPTV.equals(mPlayData.getPlayer()) && !TextUtils.isEmpty(mPlayEpisode.getExternalId())) {
                    doPptvSdkPlay();
                } else {
                    doTruePlay();
                }
            }
        }

        @Override
        public void onPreRequest() {

        }
    }

    private class AdRequestResultListener implements
            RequestResultListener<NewAdDataBean> {

        @Override
        public boolean onRequestFailed() {
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, NewAdDataBean result) {
            if (result != null) {
                AdRequestStatis.selfResponseReport(result, SelfDataConstant.AD_PO_PAUSE);
                mPauseAd = result;
                showPauseAd();
            }
        }

        @Override
        public void onPreRequest() {

        }
    }

    public void showPauseAd(){
        if(!mIsPause || mIsPlayLocalUrl){
            pauseAdLayout.setVisibility(View.GONE);
            return;
        }
        if(mIsFullScreen){
            pauseAdLayout.setLayoutParams(pauseAdFullParams);
            pauseAdImgIv.setLayoutParams(pauseAdImgFullParams);
            mPauseAdCloseIv.setLayoutParams(pauseAdDeleteFullParams);
            mPauseAdLogoIv.setLayoutParams(pauseAdLogoFullParams);
            mPauseAdTipsTv.setLayoutParams(pauseAdTipsParams);
            mPauseAdTipsTv.setTextSize(11);
        }else{
            pauseAdLayout.setLayoutParams(pauseAdHalfParams);
            pauseAdImgIv.setLayoutParams(pauseAdImgHalfParams);
            mPauseAdCloseIv.setLayoutParams(pauseAdDeleteHalfParams);
            mPauseAdLogoIv.setLayoutParams(pauseAdLogoHalfParams);
            mPauseAdTipsTv.setLayoutParams(pauseAdTipsParams);
            mPauseAdTipsTv.setTextSize(9);
        }
        if(pauseAdLayout.getVisibility() == View.VISIBLE){
            return;
        }
        if(mPauseAd != null){
            Payload payload = mPauseAd.payload;
            if (null == payload) {
                return;
            }
            if (Utils.BAIDU_AD.equals(mPauseAd.provider)) {
                BaiduInterAdView baiduAd = new BaiduInterAdView(mSelfOwnActivity, pauseAdLayout, "pause");
                baiduAd.setAdListener(new SdkPauseAdListener());
                baiduAd.setBaiduAd(((SDKPayload)payload).adId);
            } else if (Utils.GDT_AD.equals(mPauseAd.provider)) {
                GdtNativeAdView gdtAd = new GdtNativeAdView(mSelfOwnActivity, "pause", pauseAdLayout, "pause");
                gdtAd.setAdListener(new SdkPauseAdListener());
                gdtAd.loadAD(((SDKPayload)payload).adId);
            } else if (Utils.SERVER_AD.equals(mPauseAd.provider)) {
                ServerNativeAdView serverAd = new ServerNativeAdView(mSelfOwnActivity, pauseAdLayout, "pause");
                ServerPayload serverPayload = (ServerPayload)payload;
                serverAd.setServerAd(serverPayload, MoviesHttpApi.PAUSE);
            } else if (Utils.YZ_AD.equals(mPauseAd.provider)) {
                YzPayAdView yzAdView = new YzPayAdView(mSelfOwnActivity, pauseAdLayout, "pause");
                yzAdView.setYzAd(((YzPayload)mPauseAd.payload).ad);
            } else if (Utils.HZ_AD.equals(mPauseAd.provider)) {
                HzPayAdView hzAdView = new HzPayAdView(mSelfOwnActivity, pauseAdLayout, "pause");
                hzAdView.setHzAd(((HzPayload)mPauseAd.payload).ad);
            }else if (Utils.XF_AD.equals(mPauseAd.provider)) {
                XfPayAdView xfAdView = new XfPayAdView(mSelfOwnActivity, pauseAdLayout, "pause");
                xfAdView.setXfAd(((XfPayload)mPauseAd.payload).ad);
            } else if (Utils.TT_AD.equals(mPauseAd.provider)) {
                TtPayAdView ttAdView = new TtPayAdView(mSelfOwnActivity, pauseAdLayout, "pause");
                ttAdView.setTtAd(((TtPayload)mPauseAd.payload).ad);
            }
        }
    }

    private class SdkPauseAdListener implements MyOnAdListener{

        @Override
        public void onAdDismissed() {

        }

        @Override
        public void onAdFailed() {

        }

        @Override
        public void onAdPresent() {

        }

        @Override
        public void onAdSuccess(Object obj) {
            if(!mIsPause || mIsPlayLocalUrl){
                pauseAdLayout.setVisibility(View.GONE);
            }else{
                pauseAdLayout.setVisibility(View.VISIBLE);
            }
        }
    }

    //监听时间变化
    BroadcastReceiver timeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            mTimeView.setTime();
        }
    };
    public Map<String, Boolean> getmClaritymap(){
        return mClaritymap;
    }

    public void setmNetClarityListener(NetClarityListener mNetClarityListener) {
        this.mNetClarityListener = mNetClarityListener;
    }

    private NetClarityListener mNetClarityListener;

    private BroadcastReceiver batteryChangedReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
                int level = intent.getIntExtra("level", 0);
                int scale = intent.getIntExtra("scale", 100);
                // BatteryManager.BATTERY_STATUS_CHARGING 表示是充电状态
                // BatteryManager.BATTERY_STATUS_DISCHARGING 放电中
                // BatteryManager.BATTERY_STATUS_NOT_CHARGING 未充电
                // BatteryManager.BATTERY_STATUS_FULL 电池满
                int status = intent.getIntExtra("status", 0); // 电池状态
                LogUtils.e(TAG, "status" + status);
                //BatteryManager.BATTERY_STATUS_CHARGING;
                int power = level * 100 / scale;
                if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
                    //充电中
                    LogUtils.e(TAG, "充电中");
                    mBatteryView.setCharging(true);
                    mBatteryView.setPower(power);
                    if (mBatteryLightningView != null) {
                        mBatteryLightningView.setVisibility(View.VISIBLE);
                    }
                } else {
                    LogUtils.e(TAG, "充电完成");
                    mBatteryView.setCharging(false);
                    mBatteryView.setPower(power);
                    if (mBatteryLightningView != null) {
                        mBatteryLightningView.setVisibility(View.GONE);
                    }
                }
            }
        }
    };
    public class RequestFsTokenTask extends MoviesHttpAsyncTask<FsTokenBean> {
        public RequestFsTokenTask(Context context) {
            super(context);
        }

        @Override
        public LVideoDataHull<FsTokenBean> doInBackground() {
            return MoviesHttpApi.requestFsToken(new FsTokenParser());
        }

        @Override
        public void onPostExecute(int updateId, FsTokenBean result) {
            if (result != null && !TextUtils.isEmpty(result.getToken())) {
                funshionProxy.requestAndPrepare(mPlayEpisode.getPorder(),mPlayData.getFsAid(),result.getToken(),mPlayData.getmViewName(),"media",(int)mPlayData.getmPlayRecord()
                        .getSeekHistory());
            }

        }

        @Override
        public void netErr(int updateId, String errMsg) {
            super.netErr(updateId, errMsg);
        }

        @Override
        public void dataNull(int updateId, String errMsg) {
            super.dataNull(updateId, errMsg);
        }
    }

    private void showErrorCodeForDebug(int what,String letvErrorCode) {
        if (BuildConfig.DEBUG) {
            try {
                if (mSelfOwnActivity != null && mSelfOwnActivity instanceof VideoDetailActivity) {
                    String errorCode = "ErrorCode:";
                    TextView textView = (TextView) mSelfOwnActivity.findViewById(R.id.tv_video_name);
                    String text = textView.getText().toString();
                    if (!text.contains(errorCode)) {
                        if (!TextUtils.isEmpty(letvErrorCode)) {
                            text = text + " " + errorCode + letvErrorCode;
                        } else {
                            text = text + " " + errorCode + what;
                        }
                        textView.setText(text);
                    }
                }
            } catch (Exception e) {
                LogUtils.e(e.getMessage());
            }
        }
    }
}
